Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
3.8. Array.prototype.square and average on every array
Easy
Topics
This question is in
3. Array methods from scratchEvery array already has map, filter and join, though none of them is stored on the array itself: they live on one shared object that every array inherits from. Adding your own methods there makes them available on every array in the page, old and new. This is how polyfills work, and it is also how a small helper can quietly turn into a problem for other code.
Write two methods in array-math.js so that every array has them: square() and average().
Signature
[1, 2, 3].square() // returns a new array: [1, 4, 9]
[1, 2, 3].average() // returns a number: 2square(): a new array with each item multiplied by itself. Holes stay holes.average(): the sum of the items divided by how many items there are. Each item is converted withNumber(). An empty array givesNaN.
Requirements
- Every array has both methods, however it was made (a literal,
new Array,Array.of,Array.from, or a subclass ofArray). - The methods are stored once and shared: they are not own properties of each array, and
Object.keysof an array still lists only its indexes. - Each method works on the array it is called on, and neither changes that array.
square()returns a new array of the squares, keeps holes, converts number strings ("3"gives 9), and returns[]for an empty array.average()returns the mean of the items converted withNumber(). Number strings count as numbers (["1", "2"]gives 1.5, not a mean of text). An item thatNumber()cannot read, such as"a"orundefined, makes the resultNaN.Number()'s other rules apply as they are:nulland""count as 0,trueas 1 andfalseas 0, so[null].average()is 0.- Holes are not items:
[1, , 3].average()is 2. An empty array givesNaN. - The methods chain:
square()returns an array, so.average()can follow.
Examples
[1, 2, 3, -4].square(); // [1, 4, 9, 16]
[1, , 3].square(); // [1, empty, 9][1, 2, 3, 4].average(); // 2.5
["1", "2"].average(); // 1.5
[1, , 3].average(); // 2: two items
[].average(); // NaN[1, 2, 3, 4].square().average(); // 7.5Environment
- Plain JavaScript in a browser page;
array-math.jsruns first, then the tests call the methods on arrays they create. - The built-in array methods (
map,forEach,reduce…) are allowed. - Making the methods non-enumerable, so that
for…indoes not list them, is problem 3.9.
Hints
- An arrow function has no
thisof its own. Which kind of function gets the array before the dot as itsthis? - For an array with holes, is
this.lengththe number of items?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…