Skip to content

Instantly share code, notes, and snippets.

@scmx
Last active March 28, 2017 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scmx/de08088b7f3365e0e42f to your computer and use it in GitHub Desktop.
Save scmx/de08088b7f3365e0e42f to your computer and use it in GitHub Desktop.
While writing a redux reducer I ran into the issue that I wanted to remove a property from an object without mutating it. Here's how I solved it. tl;dr Just use http://devdocs.io/lodash/index#omit #redux #reducers #immutability
import test from 'ava'
import deepFreeze from 'deep-freeze'
import omit from 'lodash/omit'
test('normal delete will mutate the object', t => {
const obj = { a: 1, b: 2 }
deepFreeze(obj)
t.throws(() => delete obj.a)
})
test('naive implementation #1', t => {
function immutableDelete (obj, prop) {
const obj2 = {}
Object.keys(obj)
.filter(key => key !== prop)
.forEach(key => obj2[key] = obj[key])
return obj2
}
const obj = { a: 1, b: 2 }
deepFreeze(obj)
const obj2 = immutableDelete(obj, 'a')
t.same(obj2, { b: 2 })
})
test('naive implementation #2', t => {
function immutableDelete (obj, prop) {
return Object.keys(obj)
.filter(key => key !== prop)
.reduce((obj2, key) => {
obj2[key] = obj[key]
return obj2
}, {})
}
const obj = { a: 1, b: 2 }
deepFreeze(obj)
const obj2 = immutableDelete(obj, 'a')
t.same(obj2, { b: 2 })
})
test('ah I can just use _.omit', t => {
const obj = { a: 1, b: 2 }
deepFreeze(obj)
const obj2 = omit(obj, 'a')
t.same(obj2, { b: 2 })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment