Implement a function named each()
Similar to Javascript’s forEach, with the following signature:
each(array, callback); // ⟹ null
each()
calls the provided callback function once for every element in the provided array in ascending order.
callback()
is invoked with a single argument: the value of the element.
The callback’s signature could be:
callback(item){ /* ... */ }
Note: Do not use Array.prototype.forEach
for your implementation.
Implement a function named reduce()
, with the following signature:
reduce(array, reducer, initialValue) => reductionResult
Where reducer
is a function (given by the user) with the following signature:
reducer(accumulator, currentValue) => newValue
The reduce()
method executes a reducer function (that your user provides) on each element of the array, resulting in a single output value.
For every element in array, reduce should call the reducer with the item, and the accumulator. The return value from reducer should become the new value for accumulator, passed to the next execution, and returned at the end.
Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.
Note: You are not allowed to use any loops (for
, while
, forEach
, map
, ...) aside from each which you have implemented in #1.
Examples:
reduce([1, 2, 3], (accumulator, currentValue) => accumulator + currentValue, 0); // ⟹ 6
reduce([1, 2, 3], (accumulator, currentValue) => accumulator + currentValue, "0"); // ⟹ "0123"
Implement a function named map()
, with the following signature:
map(array, callback) => mappedArray
Where callback is a function given by the user with the signature:
callback(currentValue) => newItem
The map() method creates a new array with the results of calling a provided callback function on every element in the calling array.
Note: You are not allowed to use any loops (for
, while
, forEach
, map
, ...) aside from reduce
which you have implemented in #1.
Examples:
map([1, 2, 3], (item) => item * 2); // ⟹ [2,4,6]
map(["1", "2", "3"], (item) => item + " mississippi"); // ⟹ ["1 mississippi" , "2 mississippi" ,"3 mississippi"]
Implement a function named chunk
with the following signature:
chunk(array, chunkSize) => Array
Where chunk size is an integer. The function should return an array of arrays which are made of the original array's elements in order, each being no larger than the original array.
Note: You are not allowed to use any loops (for, while, forEach, map, ...) aside from reduce
and/or map
which you have implemented in #1.
Examples:
chunk([1,2,3,4,5,6,7,8], 4); // ⟹ [[1,2,3,4], [5,6,7,8]]
chunk([1,2,3,4,5,6,7,8], 3); // ⟹ [[1,2,3], [4,5,6], [7,8]]
chunk([1,2,3,4,5,6,7,8], 9); // ⟹ [[1,2,3,4,5,6,7,8]]