Skip to content

Iteration - reduce with deconstruction or forEach #1417

@penx

Description

@penx

I have an object:

    things = {
      table = 'red',
      chair = 'green'
    }

Adhering to Airbnb's JavaScript Style Guide, I want to create a function that duplicates this object, setting all keys of the object to blue.

My 2 options seem to be:

1 Use reduce

    function alwaysBlue(things) {
      return Object.keys(things)
        .reduce((acc, thing) => ({ ...acc, [thing]: 'blue' }), {})
    }

2 Use forEach

    function alwaysBlue(things) {
      const blueThings = {}
      Object.keys(things)
        .forEach(thing => (blueThings[thing] = 'blue'))
      return blueThings
    }

(1) deconstruction on every iteration seems expensive, but if I'm to take no-param-reassign in to account I can't just append to the accumulator on each iteration

However, forEach (2) should be avoided in favour of map() / every() / filter() / find() / findIndex() / reduce() / some(), according to https://github.com/airbnb/javascript#iterators--nope

So which is the preferred approach if I'm to adhere to Airbnb's JavaScript Style Guide - or is there another approach I'm missing?

(also posted at http://stackoverflow.com/questions/44045938/reduce-with-deconstruction-or-foreach-iteration-and-airbnb-javascript-style-gu )

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions