Apply Transform Over Each Element in an Array

Easy
25
2
58.4% Acceptance

In this lab, you have to create a function called map which takes in two arguments: an integer array arr and a mapping function fn. The function should return a new array with the transformation applied to each element such that returnedArray[i] = fn(arr[i], i).

Do not use the built-in Array.map method for this task.

Here's a verbose description of what the function should do:

  1. Iterate through each element of the input array arr.
  2. Call the mapping function fn with the current element and its index as arguments.
  3. Store the result of the called function in the corresponding index of a new array.
  4. Return the new transformed array after iterating through all the elements of the input array arr.

Consider the given examples:

Example 1:

Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; } Output: [2,3,4]

const newArray = map(arr, plusone); // [2,3,4]

Explanation: The function plusone 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]

const newArray = map(arr, plusI); // [1,3,5]

Explanation: The function plusI 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]

const newArray = map(arr, constant); // [42,42,42]

Explanation: The function constant always returns 42.

Constraints:

  • 0 <= arr.length <= 1000
  • -10^9 <= arr[i] <= 10^9
  • fn returns a number

Remember to export your map function using ESM export to be able to evaluate its functionality in the provided evaluation script. The evaluation script will import your function and perform various tests to ensure it meets all the requirements described above. You have to complete the challenges below and make sure you pass all the evaluation script tests.

Challenges

(Writing dummy challenges here. You have to create challenges for this lab.)

  1. Challenge 1
  2. Challenge 2

(Insert complete evaluation script and other files as required)