Skip to content

Commit

Permalink
Merge pull request #306 from michalkvasnicak/is-plain-object-fix
Browse files Browse the repository at this point in the history
fix isPlainObject
  • Loading branch information
gaearon committed Jul 23, 2015
2 parents 941a2e1 + 5734779 commit 0fc5802
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"babel-core": "^5.6.18",
"babel-eslint": "^3.1.15",
"babel-loader": "^5.1.4",
"contextify": "^0.1.14",
"eslint": "^0.23",
"eslint-config-airbnb": "0.0.6",
"eslint-plugin-react": "^2.3.0",
Expand Down
17 changes: 14 additions & 3 deletions src/utils/isPlainObject.js
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);
}
7 changes: 7 additions & 0 deletions test/utils/isPlainObject.spec.js
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();
});
});

0 comments on commit 0fc5802

Please sign in to comment.