Skip to content

Commit

Permalink
feat: add isPlainObject
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 11, 2018
1 parent 6f39124 commit 5502591
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export { default as isNil } from './isNil'
export { default as isNull } from './isNull'
export { default as isNumber } from './isNumber'
export { default as isObject } from './isObject'
export { default as isPlainObject } from './isPlainObject'
export { default as isRegExp } from './isRegExp'
export { default as isString } from './isString'
export { default as isUndefined } from './isUndefined'
Expand Down
17 changes: 17 additions & 0 deletions src/isPlainObject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* 检查 value 是否是一个普通对象。
*
* @param value 要检查的值
* @returns 是(true)或否(false)
*/
export default function isPlainObject(value: any): value is object {
if (!value || typeof value !== 'object') {
return false
}
const proto = Object.getPrototypeOf(value)
if (proto === null) {
return true
}
const Ctor = proto.constructor
return typeof Ctor === 'function' && Ctor instanceof Ctor
}
18 changes: 18 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,24 @@ describe('isObject', () => {
})
})

describe('isPlainObject', () => {
test('是', () => {
expect(vtils.isPlainObject({})).toBeTruthy()
expect(vtils.isPlainObject({ x: 1 })).toBeTruthy()
expect(vtils.isPlainObject(Object.create(null))).toBeTruthy()
expect(vtils.isPlainObject(Object({ x: 1 }))).toBeTruthy()
})
test('不是', () => {
const MyCls = class Cls {}
expect(vtils.isPlainObject('str')).toBeFalsy()
expect(vtils.isPlainObject(2)).toBeFalsy()
expect(vtils.isPlainObject(null)).toBeFalsy()
expect(vtils.isPlainObject(Date)).toBeFalsy()
expect(vtils.isPlainObject(() => ({}))).toBeFalsy()
expect(vtils.isPlainObject(MyCls)).toBeFalsy()
})
})

describe('isDate', () => {
test('是', () => {
expect(vtils.isDate(now)).toBeTruthy()
Expand Down

0 comments on commit 5502591

Please sign in to comment.