Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iteration - reduce with deconstruction or forEach #1417

Closed
penx opened this issue May 18, 2017 · 1 comment
Closed

Iteration - reduce with deconstruction or forEach #1417

penx opened this issue May 18, 2017 · 1 comment
Labels

Comments

@penx
Copy link

penx commented May 18, 2017

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 )

@ljharb
Copy link
Collaborator

ljharb commented May 18, 2017

Since that's invalid syntax, I assume your object is:

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

Your first example, with the reduce, is correct. "Seems expensive" is something that you shouldn't worry about - performance is the least important thing, only to be concerned about after code is correct, clean, tested, and profiled.

Only if it ends up being necessary (as determined by fully benchmarking your app, not by microbenchmarks like jsperf), then you'd use your forEach approach next, and then if it still was necessary, you'd devolve it to a for loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants