Skip to content

Commit

Permalink
Revert "Make hasProperty work with booleans and symbols"
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfcosta committed Oct 5, 2016
1 parent 6d2f6d4 commit bf3922d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 18 deletions.
29 changes: 21 additions & 8 deletions index.js
Expand Up @@ -7,15 +7,17 @@
* MIT Licensed
*/

var type = require('type-detect');

/**
* ### .hasProperty(object, name)
*
* This allows checking whether an object has own
* or inherited from prototype chain named property.
* This allows checking whether an object has
* named property or numeric array index.
*
* Basically does the same thing as the `in`
* operator but works properly with null/undefined values
* and other primitives.
* operator but works properly with natives
* and null/undefined values.
*
* var obj = {
* arr: ['a', 'b', 'c']
Expand All @@ -37,20 +39,31 @@
* hasProperty(obj.arr, 3); // false
*
* @param {Object} object
* @param {String|Symbol} name
* @param {String|Number} name
* @returns {Boolean} whether it exists
* @namespace Utils
* @name hasProperty
* @api public
*/

var literals = {
'number': Number,
'string': String,
};
function hasProperty(obj, name) {
if (typeof obj === 'undefined' || obj === null) {
var objType = type(obj);
// Bad Object, obviously no props at all
if (objType === 'null' || objType === 'undefined') {
return false;
}

// The `in` operator does not work with primitives.
return name in Object(obj);
// The `in` operator does not work with certain literals
// box these before the check
if (literals[objType] && typeof obj !== 'object') {
obj = new literals[objType](obj);
}

return name in obj;
}

/* !
Expand Down
3 changes: 3 additions & 0 deletions package.json
Expand Up @@ -49,6 +49,9 @@
"max-statements": 0
}
},
"dependencies": {
"type-detect": "^2.0.1"
},
"devDependencies": {
"browserify": "^13.0.0",
"browserify-istanbul": "^1.0.0",
Expand Down
12 changes: 2 additions & 10 deletions test/index.js
Expand Up @@ -9,23 +9,15 @@ describe('hasProperty', function () {
assert(pathval.hasProperty(arr, 3) === false);
});

it('should handle primitives', function () {
it('should handle literal types', function () {
var exampleString = 'string literal';
assert(pathval.hasProperty(exampleString, 'length') === true);
assert(pathval.hasProperty(exampleString, 3) === true);
assert(pathval.hasProperty(exampleString, 14) === false);

assert(pathval.hasProperty(1, 'foo') === false);
assert(pathval.hasProperty(false, 'bar') === false);
assert(pathval.hasProperty(true, 'toString') === true);

if (typeof Symbol === 'function') {
assert(pathval.hasProperty(Symbol(), 1) === false);
assert(pathval.hasProperty(Symbol.iterator, 'valueOf') === true);
}
});

it('should handle objects', function () {
it('should handle undefined', function () {
var exampleObj = {
foo: 'bar',
};
Expand Down

0 comments on commit bf3922d

Please sign in to comment.