[Leetcode] JS 30 Apply Transform over Each Element in Array

[Leetcode] JS 30 Apply Transform over Each Element in Array

Question 2635

high-order function

Question

Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.

The returned array should be created such that returnedArray[i] = fn(arr[i], i).

Please solve it without the built-in Array.map method.

Example 1:

Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]
Explanation:
const newArray = map(arr, plusone); // [2,3,4]
The function increases each value in the array by one.

Example 2:

Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]
Explanation: The function increases each value by the index it resides in.

Example 3:

Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
Explanation: The function always returns 42.

Constraints:

  • 0 <= arr.length <= 1000
  • -109 <= arr[i] <= 109
  • fn returns an integer.

My Solution

/**
 * @param {number[]} arr
 * @param {Function} fn
 * @return {number[]}
 */
var map = function(arr, fn) {
    result = [];
    for (let e = 0; e < arr.length; e++) {
        result.push(fn(arr[e], e));
    };
    return result 
};

My Takeaway

This question isn't that difficult. The core of this problem is using a function (fn) as a parameter to process array elements and return a new array. This is a classic application of higher-order functions.

💡
A higher-order function is a function that either:
1. Takes one or more functions as arguments, or
2. Returns a function as its result.
This is a key concept in functional programming and is widely used in JavaScript and other modern programming languages.