We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Array Prototype ForEach

Number: 2907

Difficulty: Easy

Paid? Yes

Companies: N/A


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.


Code Solutions

# Python version: Create a custom list subclass with a forEach method

class CustomList(list):
    def forEach(self, callback, context):
        # Iterate through the list by index
        for index in range(len(self)):
            # Call the callback with the context as an attribute (simulate 'this' binding)
            # In Python, we pass context as an argument since Python functions do not have implicit context binding.
            callback(self[index], index, self, context)

# Example usage:
def callback(val, index, arr, ctx):
    # Modify the array element by multiplying it by 2 (as an example)
    arr[index] = val * 2

# Create an instance of CustomList
arr = CustomList([1, 2, 3])
# Call the custom forEach method with a callback and context (context is not used directly here)
arr.forEach(callback, {"context": True})
# Now arr becomes [2, 4, 6]
print(arr)  # Output: [2, 4, 6]
← Back to All Questions