CopyDataProperties.js 1.8 KB

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