ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Apply Functional Transformation with Map

TypeScript

Goal -- WPM

Ready
Exercise Algorithm Area
1function transformArray<T, U>(arr: T[], mapFn: (item: T) => U): U[] {
2if (!arr || arr.length === 0) {
3return [];
4}
5
6const transformedArray: U[] = [];
7for (let i = 0; i < arr.length; i++) {
8transformedArray.push(mapFn(arr[i]));
9}
10
11return transformedArray;
12}
Algorithm description viewbox

Apply Functional Transformation with Map

Algorithm description:

This function applies a given transformation function to each element of an array and returns a new array containing the transformed elements. It's a fundamental functional programming pattern used for data manipulation without altering the original array. This is commonly used for tasks like converting units, formatting data, or extracting specific properties from objects within an array.

Algorithm explanation:

The `transformArray` function takes an array `arr` and a mapping function `mapFn`. It first checks if the input array is null or empty; if so, it returns an empty array. Otherwise, it initializes an empty array `transformedArray`. It then iterates through each element of the input array using a `for` loop. In each iteration, it calls the `mapFn` with the current element and pushes the returned transformed value into `transformedArray`. Finally, it returns the `transformedArray`. The time complexity is O(N) where N is the number of elements in the array, as each element is processed once by the mapping function. The space complexity is O(N) to store the new transformed array.

Pseudocode:

function transformArray(arr, mapFn):
  if arr is empty or null:
    return empty array

  transformedArray = empty array
  for each element in arr:
    transformedElement = mapFn(element)
    add transformedElement to transformedArray

  return transformedArray