Skip to main content David Edelstein's Blog

🦙
🦙

Using Immer to compress Immer patches

Published: 2018-10-10
dave@edelsteinautomotive.com
David Edelstein

Immer is a great immutable library for javascript by Michel Weststrate

Using this library and tracking patches, I’ve noticed the patch list can really grow if you are issuing updates frequently. Here’s a bit of sample code for taking a long list of patches and shortening them to only the list that gets you from the initial state to the last state.

var immer = require("immer")
var produce = immer.produce;

var patches=[];
var state0 = {a:1};
var state1 = produce(state0, function(draft){draft.b=9;}, function(p){patches.push(...p)});
var state2 = produce(state1, function(draft){draft.a=3;}, function(p){patches.push(...p)});
var state3 = produce(state2, function(draft){draft.b=99;}, function(p){patches.push(...p)});
var state4 = produce(state3, function(draft){draft.a=5;}, function(p){patches.push(...p)});

console.log(patches);
//Array (4 items)
//0: Object {op: "add", path: , value: 9}
//1: Object {op: "replace", path: , value: 3}
//2: Object {op: "replace", path: , value: 99}
//3: Object {op: "replace", path: , value: 5}

var applyPatches=immer.applyPatches;

produce(state0, function(draft){
applyPatches(draft, patches);
}, function(p){patches=p});

console.log(patches);
//Array (2 items)
//0: Object {op: "add", path: , value: 99}
//1: Object {op: "replace", path: , value: 5}

From old medium @dedels