index.js 1.2 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 defineDataProperty = require('define-data-property');
  7. var isFunction = function (fn) {
  8. return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
  9. };
  10. var supportsDescriptors = require('has-property-descriptors')();
  11. var defineProperty = function (object, name, value, predicate) {
  12. if (name in object) {
  13. if (predicate === true) {
  14. if (object[name] === value) {
  15. return;
  16. }
  17. } else if (!isFunction(predicate) || !predicate()) {
  18. return;
  19. }
  20. }
  21. if (supportsDescriptors) {
  22. defineDataProperty(object, name, value, true);
  23. } else {
  24. defineDataProperty(object, name, value);
  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;