Array Prototype ForEach

Updated on 21 May, 2025
Array Prototype ForEach header image

Problem Statement

The task is to implement a method forEach that enhances all arrays in JavaScript, allowing the method to be called as array.forEach(callback, context). This method should perform a function, callback, on each element of the array without returning any value. The method is distinctive because it processes each element based on a function defined by the user, and it allows for an optional context (context) to be passed which changes the meaning of this within the callback function.

The callback function receives three arguments:

  • currentValue - the current element of the array being processed.
  • index - the position of currentValue within the array.
  • array - the array itself, which can be manipulated or accessed wholly.

The context parameter alters the function context inside the callback, referring to the object passed. The enhancement involves implementing this feature from scratch without relying on the built-in array methods.

Examples

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

  • arr is a valid JSON array
  • context is a valid JSON object
  • fn is a function
  • 0 <= arr.length <= 105

Approach and Intuition

The aim here is to simulate the behavior of the built-in Array.prototype.forEach method but from scratch. Let's break down the approach using the provided examples:

  1. Implement Custom forEach Function:

    • The method will iterate over each element of the array.
    • It invokes the callback function for each element, passing currentValue, index, and array as arguments.
    • Ensure this within callback is bound to the context if provided.
  2. Application Insight from Examples:

    • Example 1: Multiplies each element by 2. The context isn't utilized in the transformation of the array elements. This shows how values can be modified in place.
    • Example 2: Regardless of the array content (booleans), every element in the array is replaced with the context object. This demonstrates the use of the context in transforming array entries.
    • Example 3: Uses logical negation to flip boolean values. Although context is provided, it doesn’t influence the result, illustrating that context use is optional depending on callback functionality.

From observing the examples:

  • The function should handle arrays of any length, ranging from empty to a very large number of elements (up to 105).
  • Different types of values (booleans, integers) and modifications (conditional, direct assignment, mathematical operations) showcased in examples imply that the callback function needs to be flexible.
  • Successful context manipulation highlights the significance of correctly binding this inside callback.

Overall, the implementation of a forEach method is about effectively iterating over array elements, providing flexibility in processing through callback, and properly managing execution context with context. This customized approach emphasizes JavaScript's robust handling of functions as first-class objects and showcases dynamic binding of this.

Solutions

  • JavaScript
js
Array.prototype.iterate = function(handler, ctx) {
    const origin = this;
    function deepIter(i) {
        if (i === origin.length) {
            return;
        }
        handler.call(ctx, origin[i], i, origin);
        deepIter(i + 1);
    }

    deepIter(0);
};

The provided JavaScript code defines a custom method on the Array.prototype named iterate. This method enhances the functionality of arrays by allowing a user to apply a function to each element in the array recursively. Here's how the method works:

  • The method iterate accepts two parameters:
    • handler: A function that executes for each element in the array.
    • ctx: An optional context (this value) to be used when calling the handler function.
  • Internally, the method uses a recursive function deepIter to navigate through the array:
    • It checks if the current index i is equal to the length of the array - this acts as the termination condition for the recursion.
    • The handler function is called with the current context ctx, allowing the array element, its index, and the array itself to be manipulated or utilized as needed.
    • The recursive function deepIter is then called with the next index (i + 1), continuing the iteration until the entire array is traversed.

This custom iterate method is particularly useful for scenarios needing deep or custom iteration mechanisms, especially when one wants to maintain specific contexts throughout the iteration process. Essentially, this method bridges the functionality gap between forEach-like operations and user-defined needs for context preservation and deep recursion based operations on arrays.

Comments

No comments yet.