1

I need to implement the mapping function using reduce.

Requirements:

  • The map function should apply a fn function to every element in array.
  • array should not be mutated

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!

3
  • The obvious question is why can't you just use .map()? Commented Apr 23, 2021 at 7:20
  • @phuzi that's the task - using map is forbidden. I need to impement it with reduce :) Commented Apr 23, 2021 at 7:21
  • the check is not necessary, if the array is empty it returns empty anyways Commented Apr 23, 2021 at 7:26

1 Answer 1

1

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[]);
};
Sign up to request clarification or add additional context in comments.

8 Comments

@AnnaHarshyna please use return [...acc, fn(item)]. Avoid mutation inside reduce
@captain-yossarian Care to explain? In this particular circumstance, what benefit is there?
Reduce is more functional approach. It can be used for function composition. In general, nobody expects mutation here. Btw, I believe it is better to avoid mutation of arguments. But it is only my thoughts. I respect your approach.
Nobody expects mutation of a variable local to only this function that the function itself creates? I don't understand why that would be problematic.
Are You open for explanation and arguments or You just want to argue? I'm asking, because if You are FP hater , nobody wins in this discussion
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.