ohmybuck

Reduce Usage Of Reduce

June 06, 2020

I’ve been using reduce loads for string concat but came across this twitter thread when an XO error flagged up

I’ve now just refac’d a piece of code which has arguably made it way more understandable to others.

// from this...
const stringMessageFromObject = object => {
  const reducer = (acc, curr) => acc + `${curr}: ${object[curr]}\n`
  return Object.keys(object).reduce(reducer, "")
}

// to this...
const stringMessageFromObject = object =>
  Object.keys(object)
    .map(curr => `${curr}: ${object[curr]}\n`)
    .join("")

Written by Oliver Smit. I love talking about web technologies, good design practices, optimising productivity, and rapid prototyping of projects. Check out my work on Github