Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
arr
is a valid JSON arraycontext
is a valid JSON objectfn
is a function0 <= arr.length <= 10^5
Solution
Method 1 – Polyfill Using Prototype
Intuition
We want to add a custom forEach
method to all arrays, mimicking the native behavior, including support for a callback and an optional context for this
.
Approach
Define the method on Array.prototype
. For each element, call the callback with the correct arguments and bind this
to the context.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)