index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. var keys = require('object-keys');
  3. var foreach = require('foreach');
  4. var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
  5. var toStr = Object.prototype.toString;
  6. var isFunction = function (fn) {
  7. return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
  8. };
  9. var arePropertyDescriptorsSupported = function () {
  10. var obj = {};
  11. try {
  12. Object.defineProperty(obj, 'x', { enumerable: false, value: obj });
  13. /* eslint-disable no-unused-vars, no-restricted-syntax */
  14. for (var _ in obj) { return false; }
  15. /* eslint-enable no-unused-vars, no-restricted-syntax */
  16. return obj.x === obj;
  17. } catch (e) { /* this is IE 8. */
  18. return false;
  19. }
  20. };
  21. var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported();
  22. var defineProperty = function (object, name, value, predicate) {
  23. if (name in object && (!isFunction(predicate) || !predicate())) {
  24. return;
  25. }
  26. if (supportsDescriptors) {
  27. Object.defineProperty(object, name, {
  28. configurable: true,
  29. enumerable: false,
  30. value: value,
  31. writable: true
  32. });
  33. } else {
  34. object[name] = value;
  35. }
  36. };
  37. var defineProperties = function (object, map) {
  38. var predicates = arguments.length > 2 ? arguments[2] : {};
  39. var props = keys(map);
  40. if (hasSymbols) {
  41. props = props.concat(Object.getOwnPropertySymbols(map));
  42. }
  43. foreach(props, function (name) {
  44. defineProperty(object, name, map[name], predicates[name]);
  45. });
  46. };
  47. defineProperties.supportsDescriptors = !!supportsDescriptors;
  48. module.exports = defineProperties;