Exercise 12: Higher-Order Function: Map Implementation
Problem Statement
Create a function `myMap(arr, fn)` that is a custom implementation of array.map().
Sample Output:
myMap([1, 2, 3], x => x * 2) => [2, 4, 6] myMap([1, 2, 3], (x, i) => x + i) => [1, 3, 5]
Solution
const myMap = (arr, fn) => {
const result = [];
for (let i = 0; i < arr.length; i++) result.push(fn(arr[i], i, arr));
return result;
};Explanation
Overall Goal:
- Array.map() ka custom implementation.
Real world:
- Understanding: how map works internally.
- Custom logic: modified map behavior.