0

I was on interview few days ago and at some part of my code like this:

array.reduce((acc, el) => ({
    ...acc,
    [el.id]: [el.value]
}), {})

But after discussion interviewer ask me to rewrite solution to be better performed like this:

array.reduce((acc, el) => {
  acc[el.id] = el.value;
  return acc;
}, {})

I understand, that copying accumulator every time is not a good solution, but I saw first solution so many times and though that changing accumulator by reference is a bad practice.

So, which code is preferred?

Dimabytes
  • 526
  • 1
  • 6
  • 17
  • It's like every new invention, people often misuse it lacking a deeper knowledge of what actually happens under the hood. – Roko C. Buljan Dec 29 '20 at 15:48
  • 1
    You're not using the accumulator elsewhere, so why would you copy it every time, especially for only updating a single field? – Aplet123 Dec 29 '20 at 15:50
  • 1
    "I understand that copying accumulator every time is not a good solution" <= to me, if I was a recruiter, that speaks volumes. If I was a recruiter, I want people who think logically and make decisions based on facts. Not based on practices they have seen repeated frequently – Taplar Dec 29 '20 at 15:57
  • A rule I often use is don't modify objects that are finalized. When you know you are building an object/structure it is fine to modify it. – 3limin4t0r Dec 29 '20 at 16:04
  • "*which code is preferred?*" is an opinion-based question that StackOverflow isn't really suited to answer. See the duplicate for some discussion - there are arguments for either. But if you care about performance (and the array is large), there's only one choice. – Bergi Dec 29 '20 at 16:29

1 Answers1

-1

I think your interviewer wants to see you make a for loop, when parsing a LOT of data performs better.

for example:

let acc = {}
for (let i = 0; i < array.length, i++) {
   const el = array[i];
   acc[el.id] = el.value;
}
Tomma5o
  • 57
  • 1
  • 5
  • "when parsing a LOT of data performs better" Where are you getting this information from? – Aplet123 Dec 29 '20 at 16:04
  • from my experience, we switched a reduce in a for loop and the code runs 2 times faster. and here the benchmark https://www.measurethat.net/Benchmarks/Show/2472/0/arrayreduce-vs-for-loop-vs-arrayforeach#latest_results_block – Tomma5o Dec 29 '20 at 16:15
  • @Tomma5o [Don't trust microbenchmarks!](https://mrale.ph/blog/2012/12/15/microbenchmarks-fairy-tale.html) A little change (probably making it easier for the compiler to inline the reduce callback) [causes largely different results](https://www.measurethat.net/Benchmarks/Show/11030/0/arrayreduce-vs-for-loops-vs-arrayforeach). – Bergi Dec 29 '20 at 16:36