16 May 2016

Tiny Immutables

Like many developers, I've been using top-down rendering to impose order on frontend code. To make this technique fast I like to use persistent data structures. Once I have immutable data I can skip unnecessary component updates by checking for equality (===) with the previous data. Immutable.js: a large (I consider anything 2/3 the size of jQuery to be large) but full-featured library is the obvious choice, but on smaller projects I find the dependency size hard to swallow. Instead, I've created a tiny immutables library called Copy Kitten for when Immutable.js is overkill.

    /\/\
( =( ^-^)=
 \(  ⊃C⊃
      Copy Kitten

Copy Kitten is a minimal library (~2.4kb minified, 894 bytes gzipped), designed specifically for JSON-compatible data types: strings, numbers, booleans, null, objects, and arrays. It manipulates JSON data and returns an updated copy; the original data is preserved.

The implementation is fairly simple and naive: before making an update it takes a shallow clone of the object, after the update it calls Object.freeze to prevent further changes. The API mirrors the standard Object and Array methods.

var data = copykitten.toImmutable({
    name: 'Kitten',
    toys: ['ball', 'mouse']
});

var toys2 = data.toys.push('yarn');

// data is unchanged
// toys2 is ['ball', 'mouse', 'yarn']

// data can be easily converted back to JSON
saveToys(JSON.stringify(toys2));

If this sounds useful, you can find the code on GitHub.