CopyDataProperties.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var callBound = require('call-bind/callBound');
  5. var forEach = require('../helpers/forEach');
  6. var every = require('../helpers/every');
  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 IsInteger = require('./IsInteger');
  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/11.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 sourceKeys = OwnPropertyKeys(from);
  31. forEach(sourceKeys, function (nextKey) {
  32. var excluded = false;
  33. forEach(excludedItems, function (e) {
  34. if (SameValue(e, nextKey) === true) {
  35. excluded = true;
  36. }
  37. });
  38. var enumerable = $isEnumerable(from, nextKey) || (
  39. // this is to handle string keys being non-enumerable in older engines
  40. typeof source === 'string'
  41. && nextKey >= 0
  42. && IsInteger(ToNumber(nextKey))
  43. );
  44. if (excluded === false && enumerable) {
  45. var propValue = Get(from, nextKey);
  46. CreateDataPropertyOrThrow(target, nextKey, propValue);
  47. }
  48. });
  49. return target;
  50. };