CopyDataProperties.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var callBound = require('call-bind/callBound');
  4. var forEach = require('../helpers/forEach');
  5. var every = require('../helpers/every');
  6. var some = require('../helpers/some');
  7. var OwnPropertyKeys = require('../helpers/OwnPropertyKeys');
  8. var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');
  9. var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow');
  10. var Get = require('./Get');
  11. var IsArray = require('./IsArray');
  12. var IsIntegralNumber = require('./IsIntegralNumber');
  13. var IsPropertyKey = require('./IsPropertyKey');
  14. var SameValue = require('./SameValue');
  15. var ToNumber = require('./ToNumber');
  16. var ToObject = require('./ToObject');
  17. var Type = require('./Type');
  18. // https://262.ecma-international.org/12.0/#sec-copydataproperties
  19. module.exports = function CopyDataProperties(target, source, excludedItems) {
  20. if (Type(target) !== 'Object') {
  21. throw new $TypeError('Assertion failed: "target" must be an Object');
  22. }
  23. if (!IsArray(excludedItems) || !every(excludedItems, IsPropertyKey)) {
  24. throw new $TypeError('Assertion failed: "excludedItems" must be a List of Property Keys');
  25. }
  26. if (typeof source === 'undefined' || source === null) {
  27. return target;
  28. }
  29. var from = ToObject(source);
  30. var keys = OwnPropertyKeys(from);
  31. forEach(keys, function (nextKey) {
  32. var excluded = some(excludedItems, function (e) {
  33. return SameValue(e, nextKey) === true;
  34. });
  35. /*
  36. var excluded = false;
  37. forEach(excludedItems, function (e) {
  38. if (SameValue(e, nextKey) === true) {
  39. excluded = true;
  40. }
  41. });
  42. */
  43. var enumerable = $isEnumerable(from, nextKey) || (
  44. // this is to handle string keys being non-enumerable in older engines
  45. typeof source === 'string'
  46. && nextKey >= 0
  47. && IsIntegralNumber(ToNumber(nextKey))
  48. );
  49. if (excluded === false && enumerable) {
  50. var propValue = Get(from, nextKey);
  51. CreateDataPropertyOrThrow(target, nextKey, propValue);
  52. }
  53. });
  54. return target;
  55. };