DEV Community

Vamshi Krishna
Vamshi Krishna

Posted on

Simplify reduce accumulator function code

Problem:

Consider a very simple reducer example : Find the sum of all elements in an array .

  const sum = [1, 2, 3, 4, 5].reduce((total, currentValue) => {
    total += currentValue;
    return total;
  }, 0);

OR

  const obj = [['a', 4], ['b', 3], ['c', 6]].reduce(
    (accumulator, currentValue) => {
      accumulator[currentValue[0]] = currentValue[1];
      return accumulator;
    },
    {}
  );

(These are just simple example for easy explanation, there are simpler ways to write them, for ex: second one can be replaced by Object.fromEntries)

My code base almost always have single line function expressions except for the reduce function. I never liked it until I found a way to write it in single line

Solution 1: Spread operator

The second code snippet can be refactored using spread :

  const obj = [['a', 4], ['b', 3], ['c', 6]].reduce(
    (accumulator, currentValue) => ({
      ...accumulator,
      [currentValue[0]]: currentValue[1]
    }),
    {}
  );

But this might affect the performance, hence not suggested.

Solution 2 : Comma operator

I came across this wonderful comma operator while reading the blog The JavaScript Comma Operator by Angus Croll.

Comma operator can be used to write multiple expressions in single line. The above code snippets can be refactored to :

  const sum = [1, 2, 3, 4, 5].reduce(
    (total, currentValue) => ((total += currentValue), total),
    0
  );
  const obj = [['a', 4], ['b', 3], ['c', 6]].reduce(
    (accumulator, currentValue) => (
      (accumulator[currentValue[0]] = currentValue[1]), accumulator
    ),
    {}
  );

This works on the principle that (expr1 , expr2) evaluates each expression left to right and returns the last expression value.

P.S.: This is purely to demonstrate the beauty of comma operator and for aesthetic purposes only with no real value for performance (IMHO). In fact, the original code should be preferred as it is more readable

Top comments (1)

Collapse
 
frondor profile image
Federico Vázquez

No, don't do this.

  1. You're adding performance penalizations to your code with that anti-pattern.
  2. Legible code > one liners