object.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. /**
  3. * High performance assign before node6
  4. * @param {Object} target - target object
  5. * @param {Object | Array} objects - object assign from
  6. * @return {Object} - return target object
  7. */
  8. exports.assign = function(target, objects) {
  9. if (!Array.isArray(objects)) {
  10. objects = [ objects ];
  11. }
  12. for (var i = 0; i < objects.length; i++) {
  13. var obj = objects[i];
  14. if (obj) {
  15. var keys = Object.keys(obj);
  16. for (var j = 0; j < keys.length; j++) {
  17. var key = keys[j];
  18. target[key] = obj[key];
  19. }
  20. }
  21. }
  22. return target;
  23. };
  24. exports.has = function has(obj, prop) {
  25. return Object.prototype.hasOwnProperty.call(obj, prop);
  26. };
  27. /**
  28. * Get all enumerable and ownership of property names
  29. * @param {Object} obj - detect object
  30. * @param {Boolean} [ignoreNull] - ignore null, undefined or NaN property
  31. * @return {Array<String>} property names
  32. */
  33. exports.getOwnEnumerables = function getOwnEnumerables(obj, ignoreNull) {
  34. if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
  35. return [];
  36. }
  37. return Object.keys(obj).filter(function(key) {
  38. if (ignoreNull) {
  39. var value = obj[key];
  40. if (value === null || value === undefined || Number.isNaN(value)) {
  41. return false;
  42. }
  43. }
  44. return exports.has(obj, key);
  45. });
  46. };
  47. /**
  48. * generate a real map object(clean object), no constructor, no __proto__
  49. * @param {Object} [obj] - init object, optional
  50. * @return {Object}
  51. */
  52. exports.map = function map(obj) {
  53. var map = new EmptyObject();
  54. if (!obj) {
  55. return map;
  56. }
  57. for (var key in obj) {
  58. map[key] = obj[key];
  59. }
  60. return map;
  61. };
  62. // faster way like `Object.create(null)` to get a 'clean' empty object
  63. // https://github.com/nodejs/node/blob/master/lib/events.js#L5
  64. // https://cnodejs.org/topic/571e0c445a26c4a841ecbcf1
  65. function EmptyObject() {}
  66. EmptyObject.prototype = Object.create(null);