Reimplement Array concat with holes and isConcatSpreadable
A small runtime for embedded devices ships without Array.prototype.concat, and its standard library team wants a drop-in helper that behaves the same way, including the parts most people never notice: holes in sparse arrays and the Symbol.isConcatSpreadable switch that lets any object opt in to (or out of) being spread.
Implement concatValues(...items). It returns a new array made from all of its arguments, in order.
concatValues(...items) // => new array
null) and:
Symbol.isConcatSpreadable property is not undefined, and is truthy; orundefined and the argument is an array (Array.isArray). So arrays spread by default, an array with [Symbol.isConcatSpreadable] = false is appended whole, and an array-like object with [Symbol.isConcatSpreadable] = true is spread.
null, undefined, functions, and plain objects (even array-like ones without the symbol).0 to length - 1. For array-like objects, length is converted to a number and truncated; a missing, negative or non-numeric length counts as 0.!(i in item)), the matching index in the result is also missing, and the result’s length still counts it, including trailing holes.concatValues() returns []. Do not modify the arguments.Array.prototype.concat, flat or flatMap.concatValues([1, 2], [3], [[4, 5]]); // => [1, 2, 3, [4, 5]]
concatValues([1], 'ab', 3, null); // => [1, 'ab', 3, null]
concatValues(); // => []
const sparse = concatValues([1, , 3], [4]);
sparse.length; // => 4
1 in sparse; // => false
const pair = { length: 2, 0: 'x', 1: 'y', [Symbol.isConcatSpreadable]: true };
concatValues(['w'], pair); // => ['w', 'x', 'y']
concatValues(['w'], { length: 1, 0: 'z' }); // => ['w', { length: 1, 0: 'z' }]
const locked = [1, 2];
locked[Symbol.isConcatSpreadable] = false;
concatValues([0], locked); // => [0, locked] (length 2)