Reputation: 93
I need to implement the mapping function using reduce
.
Requirements:
map
function should apply a fn
function to every element in array
.array
should not be mutatedThis 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
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