|
/*!
* Chai - hasProperty utility
* Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
* MIT Licensed
*/
var type = require('./type');
/**
* ### .hasProperty(object, name)
*
* 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 natives
* and null/undefined values.
*
* var obj = {
* arr: ['a', 'b', 'c']
* , str: 'Hello'
* }
*
* The following would be the results.
*
* hasProperty('str', obj); // true
* hasProperty('constructor', obj); // true
* hasProperty('bar', obj); // false
*
* hasProperty('length', obj.str); // true
* hasProperty(1, obj.str); // true
* hasProperty(5, obj.str); // false
*
* hasProperty('length', obj.arr); // true
* hasProperty(2, obj.arr); // true
* hasProperty(3, obj.arr); // false
*
* @param {Objuect} object
* @param {String|Number} name
* @returns {Boolean} whether it exists
* @name getPathInfo
* @api public
*/
var literals = {
'number': Number
, 'string': String
};
module.exports = function hasProperty(name, obj) {
var ot = type(obj);
// Bad Object, obviously no props at all
if(ot === 'null' || ot === 'undefined')
return false;
// The `in` operator does not work with certain literals
// box these before the check
if(literals[ot] && typeof obj !== 'object')
obj = new literals[ot](obj);
return name in obj;
};
|