Array Prototype ForEach Problem
Description
LeetCode Problem 2804.
Write your version of method forEach that enhances all arrays such that you can call the array.forEach(callback, context) method on any array and it will execute callback on each element of the array. Method forEach should not return anything.
callback accepts the following arguments:
currentValue- represents the current element being processed in the array. It is the value of the element in the current iteration.index- represents the index of the current element being processed in the array.array- represents the array itself, allowing access to the entire array within the callback function.
The context is the object that should be passed as the function context parameter to the callback function, ensuring that the this keyword within the callback function refers to this context object.
Try to implement it without using the built-in array methods.
Example 1:
Input:
arr = [1,2,3],
callback = (val, i, arr) => arr[i] = val * 2,
context = {"context":true}
Output: [2,4,6]
Explanation:
arr.forEach(callback, context)
console.log(arr) // [2,4,6]
The callback is executed on each element of the array.
Example 2:
Input:
arr = [true, true, false, false],
callback = (val, i, arr) => arr[i] = this,
context = {"context": false}
Output: [{"context":false},{"context":false},{"context":false},{"context":false}]
Explanation:
arr.forEach(callback, context)
console.log(arr) // [{"context":false},{"context":false},{"context":false},{"context":false}]
The callback is executed on each element of the array with the right context.
Example 3:
Input:
arr = [true, true, false, false],
callback = (val, i, arr) => arr[i] = !val,
context = {"context": 5}
Output: [false,false,true,true]
Constraints:
arris a valid JSON arraycontextis a valid JSON objectfnis a function0 <= arr.length <= 10^5
Solution
Approach: Plain loop with callback.call
Assign a function to Array.prototype.forEach that loops over the indices and calls callback for each one.
- Call it with
callback.call(context, this[i], i, this), so thatthisinside a regular (non-arrow) callback iscontext, and the callback gets the value, the index and the array. - Use a normal
function, not an arrow function, for the method itself, orthiswould not be the array. - Read
this.lengthin the loop condition each time, so the loop follows the array as the callback changes it. Return nothing.
Arrow-function callbacks ignore context by design; that is how Example 2 behaves.
Complexity: Time O(n) calls, space O(1).
/**
* @param {Function} callback
* @param {Object} context
* @return {void}
*/
Array.prototype.forEach = function (callback, context) {
for (let i = 0; i < this.length; i++) {
callback.call(context, this[i], i, this);
}
};