-
-
Notifications
You must be signed in to change notification settings - Fork 15.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #306 from michalkvasnicak/is-plain-object-fix
fix isPlainObject
- Loading branch information
Showing
3 changed files
with
22 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,23 @@ | ||
var fnToString = (fn) => Function.prototype.toString.call(fn); | ||
|
||
/** | ||
* @param {any} obj The object to inspect. | ||
* @returns {boolean} True if the argument appears to be a plain object. | ||
*/ | ||
export default function isPlainObject(obj) { | ||
if (!obj) { | ||
if (!obj || typeof obj !== 'object') { | ||
return false; | ||
} | ||
|
||
return typeof obj === 'object' && | ||
Object.getPrototypeOf(obj) === Object.prototype; | ||
var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype; | ||
|
||
if (proto === null) { | ||
return true; | ||
} | ||
|
||
var constructor = proto.constructor; | ||
|
||
return typeof constructor === 'function' | ||
&& constructor instanceof constructor | ||
&& fnToString(constructor) === fnToString(Object); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,24 @@ | ||
import expect from 'expect'; | ||
import isPlainObject from '../../src/utils/isPlainObject'; | ||
import contextify from 'contextify'; | ||
|
||
describe('isPlainObject', () => { | ||
it('should return true only if plain object', () => { | ||
function Test() { | ||
this.prop = 1; | ||
} | ||
|
||
const sandbox = contextify(); | ||
sandbox.run('var fromAnotherRealm = {};'); | ||
|
||
expect(isPlainObject(sandbox.fromAnotherRealm)).toBe(true); | ||
expect(isPlainObject(new Test())).toBe(false); | ||
expect(isPlainObject(new Date())).toBe(false); | ||
expect(isPlainObject([1, 2, 3])).toBe(false); | ||
expect(isPlainObject(null)).toBe(false); | ||
expect(isPlainObject()).toBe(false); | ||
expect(isPlainObject({ 'x': 1, 'y': 2 })).toBe(true); | ||
|
||
sandbox.dispose(); | ||
}); | ||
}); |