CopyDataProperties.js 1.9 KB

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