DEV Community

Vamshi Krishna
Vamshi Krishna

Posted on

4

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay