array-to-spliced.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var lengthOfArrayLike = require('../internals/length-of-array-like');
  2. var toAbsoluteIndex = require('../internals/to-absolute-index');
  3. var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');
  4. var $TypeError = TypeError;
  5. var max = Math.max;
  6. var min = Math.min;
  7. var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
  8. // https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.toSpliced
  9. // https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toSpliced
  10. module.exports = function (O, C, args) {
  11. var start = args[0];
  12. var deleteCount = args[1];
  13. var len = lengthOfArrayLike(O);
  14. var actualStart = toAbsoluteIndex(start, len);
  15. var argumentsLength = args.length;
  16. var k = 0;
  17. var insertCount, actualDeleteCount, newLen, A;
  18. if (argumentsLength === 0) {
  19. insertCount = actualDeleteCount = 0;
  20. } else if (argumentsLength === 1) {
  21. insertCount = 0;
  22. actualDeleteCount = len - actualStart;
  23. } else {
  24. insertCount = argumentsLength - 2;
  25. actualDeleteCount = min(max(toIntegerOrInfinity(deleteCount), 0), len - actualStart);
  26. }
  27. newLen = len + insertCount - actualDeleteCount;
  28. if (newLen > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed length exceeded');
  29. A = new C(newLen);
  30. for (; k < actualStart; k++) A[k] = O[k];
  31. for (; k < actualStart + insertCount; k++) A[k] = args[k - actualStart + 2];
  32. for (; k < newLen; k++) A[k] = O[k + actualDeleteCount - insertCount];
  33. return A;
  34. };