@akbr/patch-into

1.0.1 • Public • Published

patchInto 🔧

Immutably patch JS objects.

Supports nesting and caching.

Intended as a low-level function. If you are interested in immutably revising JS objects, see akbr/revise for more features.

Quickstart

var obj = {hello: "world"};

// A simple revision
var obj2 = patchInto(obj, "foo", "bar");
obj2 // {hello: "world", foo: "bar"}
obj1 // {hello: "world"}

// Burrow in
var obj3 = patchInto(obj, ["a", "b", "c"], "baz");
obj3 // {hello: "world", a:{b:{c:"baz"}}}}
obj1 // {hello: "world"}

// For multi-step operations, cache can speed things up.
var universe = {
  galaxies: {
    1: {
      name: "Milky Way"
    }
    //, ... 500
  }
};

var cache = {};
var universe2 = patchInto(universe, ["galaxies", 1, "numStars"], 100000000000, cache);
// Cache now indicates that "galaxies" and "1" have already been copied, and are thus "safe" for future mutation (w/r/t the original universe object).
// If we pass this cache to another operation, we avoid creating redundant shallow copies.
universe2 = patchInto(universe2, ["galaxies", 1, "isInhabitedBy"], ["humans", "martians"], cache);

API

patchInto(obj, path, value[, cache])

obj: an object or array.

path:

  • A string, dot notation for nesting;
  • A number;
  • An array, multiple values for nesting.

Other path types are interpreted as an empty path.

value: anything.

cache: an empty object (for a new cache) or a previous cache object. pathInto mutates cache objects so they are cumulative over multiple operations.

Changelog

1.0.1 - Invalid paths now interpreted as an empty path.

Readme

Keywords

Package Sidebar

Install

npm i @akbr/patch-into

Weekly Downloads

1

Version

1.0.1

License

MIT

Last publish

Collaborators

  • akbr