hasProperty.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*!
  2. * Chai - hasProperty utility
  3. * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
  4. * MIT Licensed
  5. */
  6. var type = require('./type');
  7. /**
  8. * ### .hasProperty(object, name)
  9. *
  10. * This allows checking whether an object has
  11. * named property or numeric array index.
  12. *
  13. * Basically does the same thing as the `in`
  14. * operator but works properly with natives
  15. * and null/undefined values.
  16. *
  17. * var obj = {
  18. * arr: ['a', 'b', 'c']
  19. * , str: 'Hello'
  20. * }
  21. *
  22. * The following would be the results.
  23. *
  24. * hasProperty('str', obj); // true
  25. * hasProperty('constructor', obj); // true
  26. * hasProperty('bar', obj); // false
  27. *
  28. * hasProperty('length', obj.str); // true
  29. * hasProperty(1, obj.str); // true
  30. * hasProperty(5, obj.str); // false
  31. *
  32. * hasProperty('length', obj.arr); // true
  33. * hasProperty(2, obj.arr); // true
  34. * hasProperty(3, obj.arr); // false
  35. *
  36. * @param {Objuect} object
  37. * @param {String|Number} name
  38. * @returns {Boolean} whether it exists
  39. * @name getPathInfo
  40. * @api public
  41. */
  42. var literals = {
  43. 'number': Number
  44. , 'string': String
  45. };
  46. module.exports = function hasProperty(name, obj) {
  47. var ot = type(obj);
  48. // Bad Object, obviously no props at all
  49. if(ot === 'null' || ot === 'undefined')
  50. return false;
  51. // The `in` operator does not work with certain literals
  52. // box these before the check
  53. if(literals[ot] && typeof obj !== 'object')
  54. obj = new literals[ot](obj);
  55. return name in obj;
  56. };