Problem Description
Implement a version of the forEach method that can be called on any array. This method should receive a callback function and an optional context, then execute the callback on every element of the array without using the built-in array iteration methods.
Key Insights
- Extend the array object to include a custom forEach method.
- Use a simple for loop to iterate over the elements.
- Use the callback's call method (or equivalent) to bind the context to each callback call.
- The method does not need to return any value.
Space and Time Complexity
Time Complexity: O(n) because we iterate over each element of the array once. Space Complexity: O(1) as no additional space is used aside from a few loop variables.
Solution
The solution involves extending the Array prototype with a new method called forEach. Inside this method, a for loop traverses the entire array. For each element, the callback is executed with three arguments: the current element’s value, its index, and the original array. Additionally, the callback is called with the provided context as its "this" value using the call method. This ensures that the callback has access to the proper context when executing, satisfying the problem requirements.