Write a function `myMap(arr, callback)` that works like Array.prototype.map without using the built-in map method.
Problem Statement
Examples
Input: myMap([1, 2, 3], x => x * 2)
Output: [2, 4, 6]
Explanation: Transforms every item through the callback.
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Implement Array.map, we consider the execution characteristics of JavaScript engines. Write a function `myMap(arr, callback)` that works like Array.prototype.map without using the built-in map method. 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 (create a new array to store results).
- Implement Logic: Handle state and transformations efficiently (loop through the array and call the callback with (element, index, array)).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function myMap(arr, callback) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(callback(arr[i], i, arr));
}
return result;
}
Complexity Analysis
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.