Add Array.prototype.squared that returns squared elements
A charting library computes variance and distances on every redraw, and the code is full of values.map((v) => v * v). The team wants a built-in-feeling helper instead: a method that every array has, just like map or filter.
Implement Array.prototype.squared(). It returns a new array where each element is the square of the element at the same index.
[1, 2, 3].squared() // => [1, 4, 9]
value * value, so NaN stays NaN, -Infinity becomes Infinity, and -0 becomes 0.3n becomes 9n.null, undefined, booleans, objects) becomes NaN. Numeric strings such as '3' are not converted.i is missing in the original (for example in [1, , 3] or new Array(3)), it is also missing in the result, but the length is the same.this.length and indexed reads, so it also works on array-like objects: Array.prototype.squared.call({ length: 2, 0: 3, 1: 4 }) returns the real array [9, 16].for...in. The starter installs it with Object.defineProperty and enumerable: false; keep that.[-3, 0.5, 10].squared();
// => [9, 0.25, 100]
[2, 5n].squared();
// => [4, 25n]
['3', null, true].squared();
// => [NaN, NaN, NaN]
[1, , 3].squared();
// => [1, <empty>, 9] (length 3, index 1 is still a hole)
const readings = [4, 6];
readings.squared(); // => [16, 36]
readings; // => [4, 6] (unchanged)
Do not use Array.prototype.map or Array.from. Write the loop yourself.