Immutability helpers with fast reads and acceptable writes
$ npm install --save timm
I know, I know... the world does not need yet another immutability library, especially with the likes of ImmutableJS and seamless-immutable around.
And yet... I felt the urge, at least just to cover my limited needs. ImmutableJS is a solid, comprehensive and highly-performant solution, but this power comes at a price: mixing up ImmutableJS's Maps and Lists with your plain objects can cause some friction, and reading those objects (in my case, more often than writing them) is not that convenient.
On the other side, seamless-immutable solves the "friction" problem by using plain objects and arrays, but seems to have some performance issues (at least in my benchmarks, see below).
Timm's approach: use plain objects and arrays and provide simple mutation functions that will probably not handle all edge cases. It is by no means a complete solution, but it covers 100% of my use cases and maybe 90% of yours, too. Suggestions are welcome!
Important notice: Timm does not freeze the objects it provides. In other words, it doesn't protect you against inadvertently modifying them in your code. I considered deeply freezing all objects with Object.freeze()
, but it is really slow. Then I considered doing this only in development, but then modifying frozen objects will silently fail in development (unless you use strict
in your code), and –worse still– succeed in production. Not good. In conclusion, be careful (or send me any suggestion!).
I prepared an initial benchmarking tool comparing read/write speeds in four cases:
- In-place editing (mutable)
- ImmutableJS
- Timm
- Seamless-immutable
All four solutions are first verified for consistency (the mutable solution obviously does not pass all tests) and then benchmarked. Benchmarks cover reading and writing object attributes at different nesting levels (root level, 2 levels and 5 levels deep), as well as replacing an object in a 1000-long array.
Feel free to run them yourself (download the repo and then npm install && npm run benchmarks
). These are my results on a Windows machine for 200k iterations:
Some conclusions from these benchmarks:
-
Reads are on par with native objects/arrays and seamless-immutable, and faster than ImmutableJS (the deeper, the faster). In fact, you cannot go faster than native objects for reading!
-
Writes are much slower than in-place edits, as expected, but are much faster than seamless-immutable (even in production mode), both for objects and arrays. Compared to ImmutableJS, object writes are faster (the deeper, the faster), whereas array writes are way slower. For timm and seamless-immutable, write times degrade linearly with array length (and probably object size), but much more slowly for ImmutableJS (logarithmically?). This is where ImmutableJS really shines.
-
Hence, what I recommend (from top to bottom):
- If you don't need immutability, well... just mutate in peace! I mean, in place
- If you need a complete, well-tested, rock-solid library and don't mind using a non-native API for reads: use ImmutableJS
- If you value using plain arrays/objects above other considerations, use timm
- If your typical use cases involve much more reading than writing, use timm as well
- If you do a lot of writes, updating items in long arrays or attributes in fat objects, use ImmutableJS
// Consume the CommonJS ES5 module (default)
import {merge} from 'timm';
const obj = timm.merge({a: 2}, {b: 3});
// Consume the native ES6 module (requires bundling)
import {merge} from 'timm/lib/timm_es6';
const obj = merge({a: 2}, {b: 3});
Note: you can use the ES6 module version with Webpack 2 and its tree-shaking feature to get really small bundles, including just the Timm functions you use. Make sure you disable babel-plugin-transform-es2015-modules-commonjs
in your babel-loader
configuration. More details here.
Returns a new array with an appended item or items.
Usage: addLast(array: Array<any>, val: Array<any>|any): Array<any>
arr = ['a', 'b']
arr2 = addLast(arr, 'c')
// ['a', 'b', 'c']
arr2 === arr
// false
arr3 = addLast(arr, ['c', 'd'])
// ['a', 'b', 'c', 'd']
Returns a new array with a prepended item or items.
Usage: addFirst(array: Array<any>, val: Array<any>|any): Array<any>
arr = ['a', 'b']
arr2 = addFirst(arr, 'c')
// ['c', 'a', 'b']
arr2 === arr
// false
arr3 = addFirst(arr, ['c', 'd'])
// ['c', 'd', 'a', 'b']
Returns a new array obtained by inserting an item or items at a specified index.
Usage: insert(array: Array<any>, idx: number, val: Array<any>|any): Array<any>
arr = ['a', 'b', 'c']
arr2 = insert(arr, 1, 'd')
// ['a', 'd', 'b', 'c']
arr2 === arr
// false
insert(arr, 1, ['d', 'e'])
// ['a', 'd', 'e', 'b', 'c']
Returns a new array obtained by removing an item at a specified index.
Usage: removeAt(array: Array<any>, idx: number): Array<any>
arr = ['a', 'b', 'c']
arr2 = removeAt(arr, 1)
// ['a', 'c']
arr2 === arr
// false
Returns a new array obtained by replacing an item at a specified index. If the provided item is the same (referentially equal to) the previous item at that position, the original array is returned.
Usage: replaceAt(array: Array<any>, idx: number, newItem: any): Array<any>
arr = ['a', 'b', 'c']
arr2 = replaceAt(arr, 1, 'd')
// ['a', 'd', 'c']
arr2 === arr
// false
// The same object is returned if there are no changes:
replaceAt(arr, 1, 'b') === arr
// true
The following types are used throughout this section
type ArrayOrObject = Array<any>|Object;
type Key = number|string;
Returns a value from an object at a given path. Works with
nested arrays and objects. If the path does not exist, it returns
undefined
.
Usage: getIn(obj: ?ArrayOrObject, path: Array<Key>): any
obj = {a: 1, b: 2, d: {d1: 3, d2: 4}, e: ['a', 'b', 'c']}
getIn(obj, ['d', 'd1'])
// 3
getIn(obj, ['e', 1])
// 'b'
Returns a new object with a modified attribute. If the provided value is the same (referentially equal to) the previous value, the original object is returned.
Usage: set(obj: ?ArrayOrObject, key: Key, val: any): ArrayOrObject
obj = {a: 1, b: 2, c: 3}
obj2 = set(obj, 'b', 5)
// {a: 1, b: 5, c: 3}
obj2 === obj
// false
// The same object is returned if there are no changes:
set(obj, 'b', 2) === obj
// true
Returns a new object with a modified nested attribute.
Notes:
- If the provided value is the same (referentially equal to) the previous value, the original object is returned.
- If the path does not exist, it will be created before setting the new value.
Usage: setIn(obj: ArrayOrObject, path: Array<Key>, val: any): ArrayOrObject
obj = {a: 1, b: 2, d: {d1: 3, d2: 4}, e: {e1: 'foo', e2: 'bar'}}
obj2 = setIn(obj, ['d', 'd1'], 4)
// {a: 1, b: 2, d: {d1: 4, d2: 4}, e: {e1: 'foo', e2: 'bar'}}
obj2 === obj
// false
obj2.d === obj.d
// false
obj2.e === obj.e
// true
// The same object is returned if there are no changes:
obj3 = setIn(obj, ['d', 'd1'], 3)
// {a: 1, b: 2, d: {d1: 3, d2: 4}, e: {e1: 'foo', e2: 'bar'}}
obj3 === obj
// true
obj3.d === obj.d
// true
obj3.e === obj.e
// true
// ... unknown paths create intermediate keys:
setIn({a: 3}, ['unknown', 'path'], 4)
// {a: 3, unknown: {path: 4}}
Returns a new object with a modified nested attribute, calculated via a user-provided callback based on the current value. If the calculated value is the same (referentially equal to) the previous value, the original object is returned.
Usage: updateIn(obj: ArrayOrObject, path: Array<Key>, fnUpdate: (prevValue: any) => any): ArrayOrObject
obj = {a: 1, d: {d1: 3, d2: 4}}
obj2 = updateIn(obj, ['d', 'd1'], function(val){return val + 1})
// {a: 1, d: {d1: 4, d2: 4}}
obj2 === obj
// false
// The same object is returned if there are no changes:
obj3 = updateIn(obj, ['d', 'd1'], function(val){return val})
// {a: 1, d: {d1: 3, d2: 4}}
obj3 === obj
// true
Returns a new object built as follows: the overlapping keys from the
second one overwrite the corresponding entries from the first one.
Similar to Object.assign()
, but immutable.
Usage:
merge(obj1: ArrayOrObject, obj2: ?ArrayOrObject): ArrayOrObject
merge(obj1: ArrayOrObject, ...objects: Array<?ArrayOrObject>): ArrayOrObject
The unmodified obj1
is returned if obj2
does not provide something
new to obj1
, i.e. if either of the following
conditions are true:
obj2
isnull
orundefined
obj2
is an object, but it is empty- All attributes of
obj2
are referentially equal to the corresponding attributes ofobj
obj1 = {a: 1, b: 2, c: 3}
obj2 = {c: 4, d: 5}
obj3 = merge(obj1, obj2)
// {a: 1, b: 2, c: 4, d: 5}
obj3 === obj1
// false
// The same object is returned if there are no changes:
merge(obj1, {c: 3}) === obj1
// true
Similar to merge()
, but merging the value at a given nested path.
Usage:
mergeIn(obj1: ArrayOrObject, path: Array<Key>, obj2: ArrayOrObject): ArrayOrObject
mergeIn(obj1: ArrayOrObject, path: Array<Key>, ...objects: Array<?ArrayOrObject>): ArrayOrObject
obj1 = {a: 1, d: {b: {d1: 3, d2: 4}}}
obj2 = {d3: 5}
obj3 = mergeIn(obj1, ['d', 'b'], obj2)
// {a: 1, d: {b: {d1: 3, d2: 4, d3: 5}}}
obj3 === obj1
// false
// The same object is returned if there are no changes:
mergeIn(obj1, ['d', 'b'], {d2: 4}) === obj1
// true
Returns an object excluding one or several attributes.
Usage: omit(obj: Object, attrs: Array<string>|string): Object
obj = {a: 1, b: 2, c: 3, d: 4}
omit(obj, 'a')
// {b: 2, c: 3, d: 4}
omit(obj, ['b', 'c'])
// {a: 1, d: 4}
// The same object is returned if there are no changes:
omit(obj, 'z') === obj1
// true
Returns a new object built as follows: undefined
keys in the first one
are filled in with the corresponding values from the second one
(even if they are null
).
Usage:
addDefaults(obj: ArrayOrObject, defaults: ArrayOrObject): ArrayOrObject
addDefaults(obj: ArrayOrObject, ...defaultObjects: Array<?ArrayOrObject>): ArrayOrObject
obj1 = {a: 1, b: 2, c: 3}
obj2 = {c: 4, d: 5, e: null}
obj3 = addDefaults(obj1, obj2)
// {a: 1, b: 2, c: 3, d: 5, e: null}
obj3 === obj1
// false
// The same object is returned if there are no changes:
addDefaults(obj1, {c: 4}) === obj1
// true
Copyright (c) Guillermo Grau Panea 2016
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.