Anna Harshyna
Anna Harshyna

Reputation: 93

Implement Map function using Reduce in TypeScript

I need to implement the mapping function using reduce.

Requirements:

This is my code so far (I'm checking if the array is empty):

function map<A, B>(array: A[], fn: (a: A) => B): B[] {
  if (array.length === 0) {
    return [];
  } 

}

Would appreciate any help!

Upvotes: 1

Views: 1451

Answers (1)

Evan Trimboli
Evan Trimboli

Reputation: 30082

You could do something like this (untested):

const map = <A, B>(array: readonly A[], fn: (a: A) => B): B[] => {
  return array.reduce((all, item) => {
    all.push(fn(item));
    return all;
  }, [] as B[]);
};

Upvotes: 1

Related Questions