array-with.js 790 B

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