JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 786
  • Score
    100M100P100Q96780F
  • License MIT

Fast and lightweight utility functions to check if a value is a plain object.

Package Exports

  • @httpx/plain-object
  • @httpx/plain-object/package.json

Readme

@httpx/plain-object

Fast and lightweight (~100B) functions to check or assert that a value is a plain object.

npm changelog codecov bundles node browserslist size downloads license

Install

$ npm install @httpx/plain-object
$ yarn add @httpx/plain-object
$ pnpm add @httpx/plain-object

Features

Documentation

πŸ‘‰ Official website or Github Readme

Usage

isPlainObject

import { isPlainObject } from '@httpx/plain-object';

// βœ…πŸ‘‡ True

isPlainObject({ key: 'value' });          // βœ… 
isPlainObject({ key: new Date() });       // βœ… 
isPlainObject(new Object());              // βœ… 
isPlainObject(Object.create(null));       // βœ… 
isPlainObject({ nested: { key: true} });  // βœ… 
isPlainObject(new Proxy({}, {}));         // βœ… 
isPlainObject({ [Symbol('tag')]: 'A' });  // βœ… 

// βœ…πŸ‘‡ (node context, workers, ...)
const runInNewContext = await import('node:vm').then(
    (mod) => mod.runInNewContext
);
isPlainObject(runInNewContext('({})'));   // βœ… 

// βŒπŸ‘‡ False

class Test { };
isPlainObject(new Test())           // ❌ 
isPlainObject(10);                  // ❌ 
isPlainObject(null);                // ❌ 
isPlainObject('hello');             // ❌ 
isPlainObject([]);                  // ❌ 
isPlainObject(new Date());          // ❌ 
isPlainObject(Math);                // ❌ Static built-in classes 
isPlainObject(Promise.resolve({})); // ❌
isPlainObject(Object.create({}));   // ❌

assertPlainObject

import { assertPlainObject } from '@httpx/plain-object';
import type { PlainObject } from '@httpx/plain-object';

function fn(value: unknown) {

    // πŸ‘‡ Throws `new TypeError('Not a plain object')` if not a plain object
    assertPlainObject(value);

    // πŸ‘‡ Throws `new TypeError('Custom message')` if not a plain object
    assertPlainObject(value, 'Custom message');

    // πŸ‘‡ Throws custom error if not a plain object
    assertPlainObject(value, () => {
        throw new HttpBadRequest('Custom message');
    });
    
    return value;
}

try {
    const value = fn({ key: 'value' });
    // βœ… Value is known to be PlainObject<unknown>
    assertType<PlainObject>(value);
} catch (error) {
    console.error(error);
}

PlainObject type

Generic

Γ¬sPlainObject and assertPlainObject accepts a generic to provide type autocompletion. Be aware that no runtime check are done. If you're looking for runtime validation, check zod, valibot or other alternatives.

import { isPlainObject } from '@httpx/plain-object';
import type { PlainObject } from '@httpx/plain-object';

type CustomType = {
    id: number;
    data?: {
        test: string[];
        attributes?: {
            url?: string | null;
            caption?: string | null;
            alternativeText?: string | null;
        } | null;
    } | null;
};

const value = { id: 1 } as unknown;

if (isPlainObject<CustomType>(value)) {
   // βœ… Value is a PlainObject with typescript autocompletion
   // Note that there's no runtime checking of keys, so they are
   // `unknown | undefined`. They will require unsing `?.` to access. 
    
  const url = value?.data?.attributes?.url; // autocompletion works
  // βœ… url is `unknown | undefined`, so in order to use it, you'll need to
  //    manually check for the type.
  if (typeof url === 'string') {
      console.log(url.toUpperCase());
  }
}

PlainObject

import { assertPlainObject } from '@httpx/plain-object';
import type { PlainObject } from '@httpx/plain-object';

function someFn(value: PlainObject) {
  //    
}

const value = { key: 'value' } as unknown;
assertPlainObject(value);
someFn(value)

Benchmarks

Performance is continuously monitored thanks to codspeed.io.

CodSpeed Badge

 RUN  v2.0.5 /home/sebastien/github/httpx/packages/plain-object

 βœ“ bench/comparative.bench.ts (6) 4778ms
   βœ“ Compare calling isPlainObject with 100x mixed types values (6) 4779ms
     name                                                           hz     min      max    mean     p75     p99    p995    p999     rme  samples
   Β· @httpx/plain-object: `isPlainObject(v)`              1,494,047.57  0.0005   8.3748  0.0007  0.0007  0.0008  0.0009  0.0047  Β±3.40%   747024   fastest
   Β· (sindresorhus/)is-plain-obj: `isPlainObj(v)`         1,314,933.16  0.0005  11.7854  0.0008  0.0007  0.0014  0.0015  0.0022  Β±6.83%   657467
   Β· @sindresorhus/is: `is.plainObject(v)`                  934,442.37  0.0009   2.1268  0.0011  0.0011  0.0015  0.0018  0.0065  Β±1.38%   467222
   Β· estoolkit:  `isPlainObject(v)`                         378,403.92  0.0020  10.3395  0.0026  0.0026  0.0035  0.0055  0.0155  Β±4.23%   189202
   Β· (jonschlinkert/)is-plain-object: `isPlainObject(v)`    629,387.99  0.0012  13.2170  0.0016  0.0015  0.0023  0.0030  0.0129  Β±6.81%   314694
   Β· lodash-es: `_.isPlainObject(v)`                         21,164.79  0.0361  11.2577  0.0472  0.0446  0.1057  0.1678  0.5020  Β±5.03%    10583   slowest


 BENCH  Summary

  @httpx/plain-object: `isPlainObject(v)` - bench/comparative.bench.ts > Compare calling isPlainObject with 100x mixed types values
    1.14x faster than (sindresorhus/)is-plain-obj: `isPlainObj(v)`
    1.60x faster than @sindresorhus/is: `is.plainObject(v)`
    2.37x faster than (jonschlinkert/)is-plain-object: `isPlainObject(v)`
    3.95x faster than estoolkit:  `isPlainObject(v)`
    70.59x faster than lodash-es: `_.isPlainObject(v)`

See benchmark file for details.

Bundle size

Bundle size is tracked by a size-limit configuration

Scenario (esm) Size (compressed)
import { isPlainObject } from '@httpx/plain-object ~ 100B
import { assertPlainObject } from '@httpx/plain-object ~ 160B
isPlainObject + assertPlainObject ~ 170B

For CJS usage (not recommended) track the size on bundlephobia.

Compatibility

Level CI Description
Node βœ… CI for 18.x, 20.x & 22.x.
Browsers βœ… > 96% on 07/2024. Mins to Chrome 96+, Firefox 90+, Edge 19+, iOS 12+, Safari 12+, Opera 77+
Edge βœ… Ensured on CI with @vercel/edge-runtime.
Typescript βœ… TS 5.0 + / are-the-type-wrong checks on CI.
ES2022 βœ… Dist files checked with es-check
Performance βœ… Monitored with codspeed.io

For older browsers: most frontend frameworks can transpile the library (ie: nextjs...)

Credits

This library wouldn't be possible without @sindresorhus is-plain-obj. It passes the same test suite and should be 100% compatible with it. Notable differences:

  • Slighly smaller bundle and performance.
  • Named export.
  • Provide a PlainObject type and assertPlainObject function.
  • Typescript convenience PlainObject type.
  • ESM and CJS formats.

Contributors

Contributions are welcome. Have a look to the CONTRIBUTING document.

Sponsors

If my OSS work brightens your day, let's take it to new heights together! Sponsor, coffee, or star – any gesture of support fuels my passion to improve. Thanks for being awesome! πŸ™β€οΈ

Special thanks to

Jetbrains logo Jetbrains logo
JetBrains Embie.be

License

MIT Β© belgattitude and contributors.