index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. var keys = require('object-keys');
  3. var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
  4. var toStr = Object.prototype.toString;
  5. var concat = Array.prototype.concat;
  6. var origDefineProperty = Object.defineProperty;
  7. var isFunction = function (fn) {
  8. return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
  9. };
  10. var hasPropertyDescriptors = require('has-property-descriptors')();
  11. var supportsDescriptors = origDefineProperty && hasPropertyDescriptors;
  12. var defineProperty = function (object, name, value, predicate) {
  13. if (name in object && (!isFunction(predicate) || !predicate())) {
  14. return;
  15. }
  16. if (supportsDescriptors) {
  17. origDefineProperty(object, name, {
  18. configurable: true,
  19. enumerable: false,
  20. value: value,
  21. writable: true
  22. });
  23. } else {
  24. object[name] = value; // eslint-disable-line no-param-reassign
  25. }
  26. };
  27. var defineProperties = function (object, map) {
  28. var predicates = arguments.length > 2 ? arguments[2] : {};
  29. var props = keys(map);
  30. if (hasSymbols) {
  31. props = concat.call(props, Object.getOwnPropertySymbols(map));
  32. }
  33. for (var i = 0; i < props.length; i += 1) {
  34. defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
  35. }
  36. };
  37. defineProperties.supportsDescriptors = !!supportsDescriptors;
  38. module.exports = defineProperties;