|
| 1 | +/** |
| 2 | + * 2635 |
| 3 | + * Apply Transform Over Each Element in Array |
| 4 | + ** |
| 5 | + * Given an integer array arr and a mapping function fn, |
| 6 | + * return a new array with a transformation applied to each element. |
| 7 | + * The returned array should be created such |
| 8 | + * that returnedArray[i] = fn(arr[i], i). |
| 9 | + * |
| 10 | + * Please solve it without the built-in Array.map method. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; } |
| 14 | + * Output: [2,3,4] |
| 15 | + * Explanation: |
| 16 | + * const newArray = map(arr, plusone); // [2,3,4] |
| 17 | + * The function increases each value in the array by one. |
| 18 | + * |
| 19 | + * Example 2: |
| 20 | + * Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; } |
| 21 | + * Output: [1,3,5] |
| 22 | + * Explanation: |
| 23 | + * The function increases each value by the index it resides in. |
| 24 | + * |
| 25 | + * Example 3: |
| 26 | + * Input: arr = [10,20,30], fn = function constant() { return 42; } |
| 27 | + * Output: [42,42,42] |
| 28 | + * Explanation: |
| 29 | + * The function always returns 42. |
| 30 | + * |
| 31 | + * Constraints: |
| 32 | + * • 0 <= arr.length <= 1000 |
| 33 | + * • -10^9 <= arr[i] <= 10^9 |
| 34 | + * • fn returns an integer. |
| 35 | + * |
| 36 | + * Hint 1: |
| 37 | + * Start by creating an array that will eventually be returned. |
| 38 | + * |
| 39 | + * Hint 2: |
| 40 | + * Loop over each element in the passed array. |
| 41 | + * Push fn(arr[i]) to the returned array. |
| 42 | + ** |
| 43 | + * https://leetcode.com/problems/apply-transform-over-each-element-in-array/ |
| 44 | +***/ |
| 45 | + |
| 46 | +/** |
| 47 | + * @param {number[]} arr |
| 48 | + * @param {Function} fn |
| 49 | + * @return {number[]} |
| 50 | +***/ |
| 51 | +const map = function(arr, fn) { |
| 52 | + const resultArr = new Array(arr.length); |
| 53 | + |
| 54 | + for (let i = 0; i < arr.length; i++) { |
| 55 | + resultArr[i] = fn(arr[i], i); |
| 56 | + } |
| 57 | + |
| 58 | + return resultArr; |
| 59 | +}; |
| 60 | + |
| 61 | +module.exports = map; |
0 commit comments