yoshuawuyts / es2020

Because in hindsight we don't need most of ES6
MIT License
126 stars 14 forks source link

spread #3

Closed davidmarkclements closed 8 years ago

davidmarkclements commented 8 years ago

spread can be useful, it reduces noise, commonly associated with an immutable approach

// returns fresh state object based on input
function move(input) {
  const payload = input.payload
  const action = input.action
  const x = payload.x
  if (action === 'up') return {...payload, x: x + 10}
  if (action === 'down') return {...payload, x: x - 10}
}

equivalent:

// returns fresh state object based on input
function move(input) {
  const payload = input.payload
  const action = input.action
  const x = payload.x
  if (action === 'up') return Object.assign({}, payload, {x: x + 10})
  if (action === 'down') return Object.assign({}, payload, {x: x - 10})
}
davidmarkclements commented 8 years ago

Also in ref to #1, here it is simplified further with destructuring

// returns fresh state object based on input
function move({payload, action}) {
  const {x} = payload
  if (action === 'up') return {...payload, x: x + 10}
  if (action === 'down') return {...payload, x: x - 10}
}
yoshuawuyts commented 8 years ago

hmmmm, most of the gains I'm seeing here are because of the destructuring. Using xtend the last example could be written as:

const xtend = require('xtend')
// returns fresh state object based on input
function move({payload, action}) {
  const {x} = payload
  if (action === 'up') return xtend(payload, {x: x + 10})
  if (action === 'down') return xtend(payload, {x: x - 10})
}

In choo returned objects are extended by default - so the big reliance on spread operators seems a bit like a redux-ism here. Or are there any other cases where a lot of object extending takes place?

Not dismissing it quite yet though, mostly curious if it's actually worth the addition as xtend is transparent and generally well understood.

kristoferjoseph commented 8 years ago

Poor mans immutable strategy.

let foo = 'thing'
let a = {
   foo: 'super',
   bar: 'contrived',
   baz: 'example'
}

let copy = {
    ...a,
   foo
}

It is a less cumbersome way to avoid common bugs associated with how JavaScript passes Arrays and Objects by reference.

yoshuawuyts commented 8 years ago

So we've decided against this for es2020, but if you want it anyway consider using https://github.com/ahdinosaur/es2040 :sparkles: