Skip to content

Instantly share code, notes, and snippets.

@brigand
Last active August 26, 2016 20:28
Show Gist options
  • Save brigand/a6eed93b06c7af7bf184c49798c0c1aa to your computer and use it in GitHub Desktop.
Save brigand/a6eed93b06c7af7bf184c49798c0c1aa to your computer and use it in GitHub Desktop.
immutable updates methods

Let's explore a few ways to do immutable updates in js. We'll start with this data:

var data = {
  foo: {
    bar: 1,
    baz: 2,
  }
};

Object.assign is part of es6, it's ugly but it's standard.

var updated = Object.assign(
  {},
  data,
  {
    foo: Object.assign(
      {},
      data.foo,
      {bar: 'updated'}
    )
  }
);

Object spread gives nicer code, but it's experimental syntax

var updated = {
  ...data,
  foo: {
    ...data.foo,
    bar: 'updated'  
  }
};

The react updates addon gives a decent syntax for deep updates. It's very flexible but still a bit clunky.

var update = require('react-addons-update');
var updated = update(data, {
  foo: {
    bar: {$set: 'updated'}
  }
});

imset is less powerful than the previous in that it can only perform one update at a time. It has, in my opinion, the best syntax, and only requires es6.

It's currently missing some tests, so I wouldn't recommend using it yet.

var imset = require('imset');
var updated = imset`${data}.foo.bar = 'updated'`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment