array-with.js 740 B

1234567891011121314151617
  1. var lengthOfArrayLike = require('../internals/length-of-array-like');
  2. var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');
  3. var $RangeError = RangeError;
  4. // https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.with
  5. // https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.with
  6. module.exports = function (O, C, index, value) {
  7. var len = lengthOfArrayLike(O);
  8. var relativeIndex = toIntegerOrInfinity(index);
  9. var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex;
  10. if (actualIndex >= len || actualIndex < 0) throw $RangeError('Incorrect index');
  11. var A = new C(len);
  12. var k = 0;
  13. for (; k < len; k++) A[k] = k === actualIndex ? value : O[k];
  14. return A;
  15. };