diff --git a/docs/typed/is-plain-object.mdx b/docs/typed/is-plain-object.mdx new file mode 100644 index 00000000..b9574afe --- /dev/null +++ b/docs/typed/is-plain-object.mdx @@ -0,0 +1,20 @@ +--- +title: isPlainObject +description: 'Determine if a value is a plain object' +group: Typed +--- + +## Basic usage + +Pass in a value and get a boolean telling you if the value is a plain object. + +```ts +import { isPlainObject } from 'radash' + +isPlainObject({}) // => true +isPlainObject(Object.create(null)) // => true + +isPlainObject([]) // => false +isPlainObject(null) // => false +isPlainObject(new Date()) // => false +``` diff --git a/src/index.ts b/src/index.ts index 03b14d7c..060eaaf1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -96,6 +96,7 @@ export { isIntString, isNumber, isObject, + isPlainObject, isPrimitive, isPromise, isString, diff --git a/src/tests/typed.test.ts b/src/tests/typed.test.ts index 12562bf4..5638d46f 100644 --- a/src/tests/typed.test.ts +++ b/src/tests/typed.test.ts @@ -78,6 +78,33 @@ describe('typed module', () => { }) }) + describe('isPlainObject function', () => { + test('returns true for object literal', () => { + const result = _.isPlainObject({}) + expect(result).toBeTruthy() + }) + test('returns true for Object.create(null)', () => { + const result = _.isPlainObject(Object.create(null)) + expect(result).toBeTruthy() + }) + test('returns false for non-plain object', () => { + const result = _.isPlainObject(new Date()) + expect(result).toBeFalsy() + }) + test('returns false for array', () => { + const result = _.isPlainObject([1, 2, 3]) + expect(result).toBeFalsy() + }) + test('returns false for null', () => { + const result = _.isPlainObject(null) + expect(result).toBeFalsy() + }) + test('returns false for undefined', () => { + const result = _.isPlainObject(undefined) + expect(result).toBeFalsy() + }) + }) + describe('isPrimitive function', () => { test('returns true for all the primitives', () => { const arr = [ diff --git a/src/typed.ts b/src/typed.ts index a7c46750..8d61a947 100644 --- a/src/typed.ts +++ b/src/typed.ts @@ -1,3 +1,5 @@ +const toString = /* @__PURE__ */ Object.prototype.toString + export const isSymbol = (value: any): value is symbol => { return !!value && value.constructor === Symbol } @@ -8,6 +10,14 @@ export const isObject = (value: any): value is object => { return !!value && value.constructor === Object } +export const isPlainObject = (value: any): value is object => { + if (toString.call(value) !== '[object Object]') { + return false + } + const proto = Object.getPrototypeOf(value) + return proto === null || proto === Object.getPrototypeOf({}) +} + /** * Checks if the given value is primitive. * @@ -55,7 +65,7 @@ export const isNumber = (value: any): value is number => { } export const isDate = (value: any): value is Date => { - return Object.prototype.toString.call(value) === '[object Date]' + return toString.call(value) === '[object Date]' } /**