index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 arePropertyDescriptorsSupported = function () {
  11. var obj = {};
  12. try {
  13. origDefineProperty(obj, 'x', { enumerable: false, value: obj });
  14. // eslint-disable-next-line no-unused-vars, no-restricted-syntax
  15. for (var _ in obj) { // jscs:ignore disallowUnusedVariables
  16. return false;
  17. }
  18. return obj.x === obj;
  19. } catch (e) { /* this is IE 8. */
  20. return false;
  21. }
  22. };
  23. var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
  24. var defineProperty = function (object, name, value, predicate) {
  25. if (name in object && (!isFunction(predicate) || !predicate())) {
  26. return;
  27. }
  28. if (supportsDescriptors) {
  29. origDefineProperty(object, name, {
  30. configurable: true,
  31. enumerable: false,
  32. value: value,
  33. writable: true
  34. });
  35. } else {
  36. object[name] = value;
  37. }
  38. };
  39. var defineProperties = function (object, map) {
  40. var predicates = arguments.length > 2 ? arguments[2] : {};
  41. var props = keys(map);
  42. if (hasSymbols) {
  43. props = concat.call(props, Object.getOwnPropertySymbols(map));
  44. }
  45. for (var i = 0; i < props.length; i += 1) {
  46. defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
  47. }
  48. };
  49. defineProperties.supportsDescriptors = !!supportsDescriptors;
  50. module.exports = defineProperties;