Write a function `myReduce(arr, callback, initialValue)` that works like Array.prototype.reduce.
Problem Statement
<p>Write a function <code>myReduce(arr, callback, initialValue)</code> that works like Array.prototype.reduce.</p>
Examples
Input: myReduce([1, 2, 3, 4], (acc, x) => acc + x, 0)
Output: 10
Explanation: Accumulates array items into a single final value.
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
š” Hint 1:
If initialValue is provided, start with it. Otherwise use arr[0] and start from index 1.
š” Hint 2:
Accumulate the result by calling callback(acc, currentValue, index, arr).
š” Hint 3:
Handle the case where no initialValue is given and the array is not empty.
Editorial & Approach
Problem Overview & Intuition
To solve Implement Array.reduce, we consider the execution characteristics of JavaScript engines. Write a function `myReduce(arr, callback, initialValue)` that works like Array.prototype.reduce. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (if initialvalue is provided, start with it. otherwise use arr[0] and start from index 1).
- Implement Logic: Handle state and transformations efficiently (accumulate the result by calling callback(acc, currentvalue, index, arr)).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function myReduce(arr, callback, initialValue) {
let acc = initialValue !== undefined ? initialValue : arr[0];
const startIndex = initialValue !== undefined ? 0 : 1;
for (let i = startIndex; i < arr.length; i++) {
acc = callback(acc, arr[i], i, arr);
}
return acc;
}
Complexity Analysis
Time Complexity
O(N) single linear scan through array
Space Complexity
O(N) new output array (O(1) for reduce)
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.