Mutative: Efficient immutable updates, more than 10x faster than Immer

https://github.com/unadlib/mutative

Mutative

Mutative Logo

Node CI Coverage Status npm NPM Downloads license

Mutative - A JavaScript library for efficient immutable updates, 2-6x faster than naive handcrafted reducer, and more than 10x faster than Immer.

Why is Mutative faster than the spread operation(naive handcrafted reducer)?

The spread operation has performance pitfalls, which can be detailed in the following article:

And Mutative optimization focus on shallow copy optimization, more complete lazy drafts, finalization process optimization, and more.

Motivation

Writing immutable updates by hand is usually difficult, prone to errors, and cumbersome. Immer helps us write simpler immutable updates with "mutative" logic.

But its performance issue causes a runtime performance overhead. Immer must have auto-freeze enabled by default(Performance will be worse if auto-freeze is disabled), such immutable state with Immer is not common. In scenarios such as cross-processing, remote data transfer, etc., these immutable data must be constantly frozen.

There are more parts that could be improved, such as better type inference, non-intrusive markup, support for more types of immutability, Safer immutability, more edge cases, and so on.

This is why Mutative was created.

Mutative vs Naive Handcrafted Reducer Performance

Mutative vs Reducer benchmark by object:
  • Naive handcrafted reducer
// baseState type: Record<string, { value: number }>
const state = {
  ...baseState,
  key0: {
    ...baseState.key0,
    value: i,
  },
};
  • Mutative
const state = create(baseState, (draft) => {
  draft.key0.value = i;
});

Mutative vs Reducer benchmark by object

Measure(seconds) to update the 1K-100K items object, lower is better(view source).

Mutative is up to 2x faster than naive handcrafted reducer for updating immutable objects.

Mutative vs Reducer benchmark by array:
  • Naive handcrafted reducer
// baseState type: { value: number }[]
// slower 6x than Mutative
const state = [
  { ...baseState[0], value: i },
  ...baseState.slice(1, baseState.length),
];
// slower 2.5x than Mutative
// const state = baseState.map((item, index) =>
//   index === 0 ? { ...item, value: i } : item
// );
// same performance as Mutative
// const state = [...baseState];
// state[0] = { ...baseState[0], value: i };

The actual difference depends on which spread operation syntax you use.

  • Mutative
const state = create(baseState, (draft) => {
  draft[0].value = i;
});

Mutative vs Reducer benchmark by array

Measure(seconds) to update the 1K-100K items array, lower is better(view source).

Mutative is up to 6x faster than naive handcrafted reducer for updating immutable arrays.

Mutative vs Immer Performance

Mutative passed all of Immer's test cases.

Measure(ops/sec) to update 50K arrays and 1K objects, bigger is better(view source). [Mutative v1.0.11 vs Immer v10.1.1]

Benchmark

Naive handcrafted reducer - No Freeze x 4,469 ops/sec ±0.82% (99 runs sampled)
Mutative - No Freeze x 6,015 ops/sec ±1.17% (94 runs sampled)
Immer - No Freeze x 5.36 ops/sec ±0.28% (18 runs sampled)
Mutative - Freeze x 959 ops/sec ±0.90% (99 runs sampled)
Immer - Freeze x 382 ops/sec ±0.53% (94 runs sampled)
Mutative - Patches and No Freeze x 970 ops/sec ±0.99% (96 runs sampled)
Immer - Patches and No Freeze x 5.22 ops/sec ±0.80% (18 runs sampled)
Mutative - Patches and Freeze x 505 ops/sec ±0.85% (93 runs sampled)
Immer - Patches and Freeze x 275 ops/sec ±0.49% (89 runs sampled)
The fastest method is Mutative - No Freeze

Run yarn benchmark to measure performance.

OS: macOS 14.6.1, CPU: Apple M1 Max, Node.js: v20.11.0

Immer relies on auto-freeze to be enabled, if auto-freeze is disabled, Immer will have a huge performance drop and Mutative will have a huge performance lead, especially with large data structures it will have a performance lead of more than 50x.

So if you are using Immer, you will have to enable auto-freeze for performance. Mutative is disabled auto-freeze by default. With the default configuration of both, we can see the 16x performance gap between Mutative (6,015 ops/sec) and Immer (382 ops/sec).

Overall, Mutative has a huge performance lead over Immer in more performance testing scenarios. Run yarn performance to get all the performance results locally.

More Performance Testing Scenarios, Mutative is up to `2.5X-82.9` faster than Immer:

Mutative vs Immer - All benchmark results by average multiplier

view source.

Features and Benefits

  • Mutation makes immutable updates - Immutable data structures supporting objects, arrays, Sets and Maps.
  • High performance - 10x faster than immer by default, even faster than naive handcrafted reducer.
  • Optional freezing state - No freezing of immutable data by default.
  • Support for JSON Patch - Full compliance with JSON Patch specification.
  • Custom shallow copy - Support for more types of immutable data.
  • Support mark for immutable and mutable data - Allows for non-invasive marking.
  • Safer mutable data access in strict mode - It brings more secure immutable updates.
  • Support for reducer - Support reducer function and any other immutable state library.

Difference between Mutative and Immer

Mutative Immer
Custom shallow copy
Strict mode
No data freeze by default
Non-invasive marking
Complete freeze data
Non-global config
async draft function
Fully compatible with JSON Patch spec

Mutative has fewer bugs such as accidental draft escapes than Immer, view details.

Installation

Yarn

NPM

CDN

  • Unpkg: <script src="https://unpkg.com/mutative"></script>
  • JSDelivr: <script src="https://cdn.jsdelivr.net/npm/mutative"></script>

Usage

import { create } from 'mutative';
const baseState = {
  foo: 'bar',
  list: [{ text: 'coding' }],
};
const state = create(baseState, (draft) => {
  draft.list.push({ text: 'learning' });
});
expect(state).not.toBe(baseState);
expect(state.list).not.toBe(baseState.list);

create(baseState, (draft) => void, options?: Options): newState

The first argument of create() is the base state. Mutative drafts it and passes it to the arguments of the draft function, and performs the draft mutation until the draft function finishes, then Mutative will finalize it and produce the new state.

Use create() for more advanced features by setting options.

APIs

create()

Use create() for draft mutation to get a new state, which also supports currying.

import { create } from 'mutative';
const baseState = {
  foo: 'bar',
  list: [{ text: 'todo' }],
};
const state = create(baseState, (draft) => {
  draft.foo = 'foobar';
  draft.list.push({ text: 'learning' });
});

In this basic example, the changes to the draft are 'mutative' within the draft callback, and create() is finally executed with a new immutable state.

create(state, fn, options)

Then options is optional.

  • strict - boolean, the default is false.

    Forbid accessing non-draftable values in strict mode(unless using unsafe()).

    When strict mode is enabled, mutable data can only be accessed using unsafe().

    It is recommended to enable strict in development mode and disable strict in production mode. This will ensure safe explicit returns and also keep good performance in the production build. If the value that does not mix any current draft or is undefined is returned, then use rawReturn().

    If you'd like to enable strict mode by default in a development build and turn it off for production, you can use strict: process.env.NODE_ENV !== 'production'.

  • enablePatches - boolean | { pathAsArray?: boolean; arrayLengthAssignment?: boolean; }, the default is false.

    Enable patch, and return the patches/inversePatches.

    If you need to set the shape of the generated patch in more detail, then you can set pathAsArray and arrayLengthAssignmentpathAsArray default value is true, if it's true, the path will be an array, otherwise it is a string; arrayLengthAssignment default value is true, if it's true, the array length will be included in the patches, otherwise no include array length(NOTE: If arrayLengthAssignment is false, it is fully compatible with JSON Patch spec, but it may have additional performance loss), view related discussions.

  • enableAutoFreeze - boolean, the default is false.

    Enable autoFreeze, and return frozen state, and enable circular reference checking only in development mode.

  • mark - (target) => ('mutable'|'immutable'|function) | (target) => ('mutable'|'immutable'|function)[]

    Set a mark to determine if the value is mutable or if an instance is an immutable, and it can also return a shallow copy function(AutoFreeze and Patches should both be disabled, Some patches operation might not be equivalent). When the mark function is (target) => 'immutable', it means all the objects in the state structure are immutable. In this specific case, you can totally turn on AutoFreeze and Patches. mark supports multiple marks, and the marks are executed in order, and the first mark that returns a value will be used. When a object tree node is marked by the mark function as mutable, all of its child nodes will also not be drafted by Mutative and will retain their original values.

create() - Currying

  • create draft
const [draft, finalize] = create(baseState);
draft.foobar.bar = 'baz';
const state = finalize();

Support set options such as const [draft, finalize] = create(baseState, { enableAutoFreeze: true });

  • create producer
const produce = create((draft) => {
  draft.foobar.bar = 'baz';
});
const state = produce(baseState);

Also support set options such as const produce = create((draft) => {}, { enableAutoFreeze: true });

apply()

Use apply() for applying patches to get the new state.

import { create, apply } from 'mutative';
const baseState = {
  foo: 'bar',
  list: [{ text: 'todo' }],
};
const [state, patches, inversePatches] = create(
  baseState,
  (draft) => {
    draft.foo = 'foobar';
    draft.list.push({ text: 'learning' });
  },
  {
    enablePatches: true,
  }
);
const nextState = apply(baseState, patches);
expect(nextState).toEqual(state);
const prevState = apply(state, inversePatches);
expect(prevState).toEqual(baseState);

current()

Get the current value from a draft.

  • For any draft where a child node has been modified, the state obtained by executing current() each time will be a new reference object.
  • For a draft where no child nodes have been modified, executing current() will always return the original state.

It is recommended to minimize the number of times current() is executed when performing read-only operations, ideally executing it only once.

const state = create({ a: { b: { c: 1 } }, d: { f: 1 } }, (draft) => {
  draft.a.b.c = 2;
  expect(current(draft.a)).toEqual({ b: { c: 2 } });
  // The node `a` has been modified.
  expect(current(draft.a) === current(draft.a)).toBeFalsy();
  // The node `d` has not been modified.
  expect(current(draft.d) === current(draft.d)).toBeTruthy();
});

original()

Get the original value from a draft.

const baseState = {
  foo: 'bar',
  list: [{ text: 'todo' }],
};
const state = create(baseState, (draft) => {
  draft.foo = 'foobar';
  draft.list.push({ text: 'learning' });
  expect(original(draft.list)).toEqual([{ text: 'todo' }]);
});

unsafe()

When strict mode is enabled, mutable data can only be accessed using unsafe().

const baseState = {
  list: [],
  date: new Date(),
};
const state = create(
  baseState,
  (draft) => {
    unsafe(() => {
      draft.date.setFullYear(2000);
    });
    // or return the mutable data:
    // const date = unsafe(() => draft.date);
  },
  {
    strict: true,
  }
);

If you'd like to enable strict mode by default in a development build and turn it off for production, you can use strict: process.env.NODE_ENV !== 'production'.

isDraft()

Check if a value is a draft.

const baseState = {
  date: new Date(),
  list: [{ text: 'todo' }],
};
const state = create(baseState, (draft) => {
  expect(isDraft(draft.date)).toBeFalsy();
  expect(isDraft(draft.list)).toBeTruthy();
});

isDraftable()

Check if a value is draftable

const baseState = {
  date: new Date(),
  list: [{ text: 'todo' }],
};
expect(isDraftable(baseState.date)).toBeFalsy();
expect(isDraftable(baseState.list)).toBeTruthy();

You can set a mark to determine if the value is draftable, and the mark function should be the same as passing in create() mark option.

rawReturn()

For return values that do not contain any drafts, you can use rawReturn() to wrap this return value to improve performance. It ensure that the return value is only returned explicitly.

const baseState = { id: 'test' };
const state = create(baseState as { id: string } | undefined, (draft) => {
  return rawReturn(undefined);
});
expect(state).toBe(undefined);

If the return value mixes drafts, you should not use rawReturn().

const baseState = { a: 1, b: { c: 1 } };
const state = create(baseState, (draft) => {
  if (draft.b.c === 1) {
    return {
      ...draft,
      a: 2,
    };
  }
});
expect(state).toEqual({ a: 2, b: { c: 1 } });
expect(isDraft(state.b)).toBeFalsy();

If you use rawReturn(), we recommend that you enable strict mode in development.

const baseState = { a: 1, b: { c: 1 } };
const state = create(
  baseState,
  (draft) => {
    if (draft.b.c === 1) {
      return rawReturn({
        ...draft,
        a: 2,
      });
    }
  },
  {
    strict: true,
  }
);
// it will warn `The return value contains drafts, please don't use 'rawReturn()' to wrap the return value.` in strict mode.
expect(state).toEqual({ a: 2, b: { c: 1 } });
expect(isDraft(state.b)).toBeFalsy();

makeCreator()

makeCreator() only takes options as the first argument, resulting in a custom create() function.

const baseState = {
  foo: {
    bar: 'str',
  },
};
const create = makeCreator({
  enablePatches: true,
});
const [state, patches, inversePatches] = create(baseState, (draft) => {
  draft.foo.bar = 'new str';
});

markSimpleObject()

markSimpleObject() is a mark function that marks all objects as immutable.

const baseState = {
  foo: {
    bar: 'str',
  },
  simpleObject: Object.create(null),
};
const state = create(
  baseState,
  (draft) => {
    draft.foo.bar = 'new str';
    draft.simpleObject.a = 'a';
  },
  {
    mark: markSimpleObject,
  }
);
expect(state.simpleObject).not.toBe(baseState.simpleObject);

View more API docs.

Using TypeScript

  • castDraft()
  • castImmutable()
  • Draft<T>
  • Immutable<T>
  • Patches
  • Patch
  • Options<O, F>

Integration with React

  • use-mutative - A 2-6x faster alternative to useState with spread operation
  • use-travel - A React hook for state time travel with undo, redo, reset and archive functionalities.
  • zustand-mutative - A Mutative middleware for Zustand enhances the efficiency of immutable state updates.

FAQs

  • I'm already using Immer, can I migrate smoothly to Mutative?

Yes. Unless you have to be compatible with Internet Explorer, Mutative supports almost all of Immer features, and you can easily migrate from Immer to Mutative.

Migration is also not possible for React Native that does not support Proxy. React Native uses a new JS engine during refactoring - Hermes, and it (if < v0.59 or when using the Hermes engine on React Native < v0.64) does not support Proxy on Android, but React Native v0.64 with the Hermes engine support Proxy.

  • Can Mutative be integrated with Redux?

Yes. Mutative supports return values for reducer, and redux-toolkit is considering support for configurable produce().

Migration from Immer to Mutative

mutative-compat - Mutative wrapper with full Immer API compatibility, you can use it to quickly migrate from Immer to Mutative.

  1. produce() -> create()

Mutative auto freezing option is disabled by default, Immer auto freezing option is enabled by default (if disabled, Immer performance will have a more huge drop).

You need to check if auto freezing has any impact on your project. If it depends on auto freezing, you can enable it yourself in Mutative.

import produce from 'immer';
const nextState = produce(baseState, (draft) => {
  draft[1].done = true;
  draft.push({ title: 'something' });
});

Use Mutative

import { create } from 'mutative';
const nextState = create(baseState, (draft) => {
  draft[1].done = true;
  draft.push({ title: 'something' });
});
  1. Patches
import { produceWithPatches, applyPatches } from 'immer';
enablePatches();
const baseState = {
  age: 33,
};
const [nextState, patches, inversePatches] = produceWithPatches(
  baseState,
  (draft) => {
    draft.age++;
  }
);
const state = applyPatches(nextState, inversePatches);
expect(state).toEqual(baseState);

Use Mutative

import { create, apply } from 'mutative';
const baseState = {
  age: 33,
};
const [nextState, patches, inversePatches] = create(
  baseState,
  (draft) => {
    draft.age++;
  },
  {
    enablePatches: true,
  }
);
const state = apply(nextState, inversePatches);
expect(state).toEqual(baseState);
  1. Return undefined
import produce, { nothing } from 'immer';
const nextState = produce(baseState, (draft) => {
  return nothing;
});

Use Mutative

import { create, rawReturn } from 'mutative';
const nextState = create(baseState, (draft) => {
  return rawReturn(undefined);
});

Contributing

Mutative goal is to provide efficient and immutable updates. The focus is on performance improvements and providing better APIs for better development experiences. We are still working on it and welcome PRs that may help Mutative.

Development Workflow:

  • Clone Mutative repo.
  • Run yarn install to install all the dependencies.
  • Run yarn prettier to format the code.
  • yarn test --watch runs an interactive test watcher.
  • Run yarn commit to make a git commit.

License

Mutative is MIT licensed.

{
"by": "nnx",
"descendants": 0,
"id": 40245231,
"score": 1,
"time": 1714722414,
"title": "Mutative: Efficient immutable updates, more than 10x faster than Immer",
"type": "story",
"url": "https://github.com/unadlib/mutative"
}
{
"author": "unadlib",
"date": null,
"description": "Efficient immutable updates, 2-6x faster than naive handcrafted reducer, and more than 10x faster than Immer. - unadlib/mutative",
"image": "https://opengraph.githubassets.com/8f2dd3e60cbc0f37cc83bfacdfd9aa2d5f8eec0924e089eb6f5f9cdc384e5933/unadlib/mutative",
"logo": "https://logo.clearbit.com/github.com",
"publisher": "GitHub",
"title": "GitHub - unadlib/mutative: Efficient immutable updates, 2-6x faster than naive handcrafted reducer, and more than 10x faster than Immer.",
"url": "https://github.com/unadlib/mutative"
}
{
"url": "https://github.com/unadlib/mutative",
"title": "GitHub - unadlib/mutative: Efficient immutable updates, 2-6x faster than naive handcrafted reducer, and more than 10x faster than Immer.",
"description": "Mutative Mutative - A JavaScript library for efficient immutable updates, 2-6x faster than naive handcrafted reducer, and more than 10x faster than Immer. Why is Mutative faster than the spread...",
"links": [
"https://github.com/unadlib/mutative"
],
"image": "https://opengraph.githubassets.com/8f2dd3e60cbc0f37cc83bfacdfd9aa2d5f8eec0924e089eb6f5f9cdc384e5933/unadlib/mutative",
"content": "<div><article><p></p><h2>Mutative</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#mutative\"></a><p></p>\n<p><a target=\"_blank\" href=\"https://mutative.js.org/\"><img src=\"https://raw.githubusercontent.com/unadlib/mutative/main/website/static/img/%20mutative.png\" alt=\"Mutative Logo\" /></a></p>\n<p><a target=\"_blank\" href=\"https://github.com/unadlib/mutative/workflows/Node%20CI/badge.svg\"><img src=\"https://github.com/unadlib/mutative/workflows/Node%20CI/badge.svg\" alt=\"Node CI\" /></a>\n<a target=\"_blank\" href=\"https://coveralls.io/github/unadlib/mutative?branch=main\"><img src=\"https://camo.githubusercontent.com/7b522d44eb05406c853b8ee934e89f02135a39da51a07402df99778adca4bf28/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f756e61646c69622f6d757461746976652f62616467652e7376673f6272616e63683d6d61696e\" alt=\"Coverage Status\" /></a>\n<a target=\"_blank\" href=\"https://www.npmjs.com/package/mutative\"><img src=\"https://camo.githubusercontent.com/71971e6694d46567543113ea896201477cad153415134897186339cdfcee8927/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f762f6d757461746976652e737667\" alt=\"npm\" /></a>\n<a target=\"_blank\" href=\"https://npmtrends.com/mutative\"><img src=\"https://camo.githubusercontent.com/67d410b3acd507ecfcd0f0445fc7c2ce957b43aab2a7971f7290af8c6b279322/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f646d2f6d75746174697665\" alt=\"NPM Downloads\" /></a>\n<a target=\"_blank\" href=\"https://camo.githubusercontent.com/ecb8970c534397ee6eb0a74a303d8403194281c6dd788bb2c4b22a19f14d2e31/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f6c2f6d75746174697665\"><img src=\"https://camo.githubusercontent.com/ecb8970c534397ee6eb0a74a303d8403194281c6dd788bb2c4b22a19f14d2e31/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f6c2f6d75746174697665\" alt=\"license\" /></a></p>\n<p><strong>Mutative</strong> - A JavaScript library for efficient immutable updates, 2-6x faster than naive handcrafted reducer, and more than 10x faster than Immer.</p>\n<p><strong>Why is Mutative faster than the spread operation(naive handcrafted reducer)?</strong></p>\n<p>The spread operation has performance pitfalls, which can be detailed in the following article:</p>\n<ul>\n<li><a target=\"_blank\" href=\"https://www.richsnapp.com/article/2019/06-09-reduce-spread-anti-pattern\">The reduce ({...spread}) anti-pattern</a></li>\n<li><a target=\"_blank\" href=\"https://jonlinnell.co.uk/articles/spread-operator-performance?fbclid=IwAR0mElQwz2aOxl8rcsqoYwkcQDlcXcwuyIsTmTAbmyzrarysS8-BC1lSY9k\">How slow is the Spread operator in JavaScript?</a></li>\n</ul>\n<p>And Mutative optimization focus on shallow copy optimization, more complete lazy drafts, finalization process optimization, and more.</p>\n<p></p><h2>Motivation</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#motivation\"></a><p></p>\n<p>Writing immutable updates by hand is usually difficult, prone to errors, and cumbersome. Immer helps us write simpler immutable updates with \"mutative\" logic.</p>\n<p>But its performance issue causes a runtime performance overhead. Immer must have auto-freeze enabled by default(Performance will be worse if auto-freeze is disabled), such immutable state with Immer is not common. In scenarios such as cross-processing, remote data transfer, etc., these immutable data must be constantly frozen.</p>\n<p>There are more parts that could be improved, such as better type inference, non-intrusive markup, support for more types of immutability, Safer immutability, <a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/test/immer-non-support.test.ts\">more edge cases</a>, and so on.</p>\n<p>This is why Mutative was created.</p>\n<p></p><h2>Mutative vs Naive Handcrafted Reducer Performance</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#mutative-vs-naive-handcrafted-reducer-performance\"></a><p></p>\n<details>\n<summary><b>Mutative vs Reducer benchmark by object: </b></summary>\n<ul>\n<li>Naive handcrafted reducer</li>\n</ul>\n<div><pre><span>// baseState type: Record&lt;string, { value: number }&gt;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>{</span>\n ...<span>baseState</span><span>,</span>\n <span>key0</span>: <span>{</span>\n ...<span>baseState</span><span>.</span><span>key0</span><span>,</span>\n <span>value</span>: <span>i</span><span>,</span>\n <span>}</span><span>,</span>\n<span>}</span><span>;</span></pre></div>\n<ul>\n<li>Mutative</li>\n</ul>\n<div><pre><span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>key0</span><span>.</span><span>value</span> <span>=</span> <span>i</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p><a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/benchmark-object.jpg\"><img src=\"https://github.com/unadlib/mutative/raw/main/benchmark-object.jpg\" alt=\"Mutative vs Reducer benchmark by object\" /></a></p>\n<blockquote>\n<p>Measure(seconds) to update the 1K-100K items object, lower is better(<a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/test/performance/benchmark-object.ts\">view source</a>).</p>\n</blockquote>\n</details>\n<p>Mutative is up to 2x faster than naive handcrafted reducer for updating immutable objects.</p>\n<details>\n<summary><b>Mutative vs Reducer benchmark by array: </b></summary>\n<ul>\n<li>Naive handcrafted reducer</li>\n</ul>\n<div><pre><span>// baseState type: { value: number }[]</span>\n<span>// slower 6x than Mutative</span>\n<span>const</span> <span>state</span> <span>=</span> <span>[</span>\n <span>{</span> ...<span>baseState</span><span>[</span><span>0</span><span>]</span><span>,</span> <span>value</span>: <span>i</span> <span>}</span><span>,</span>\n ...<span>baseState</span><span>.</span><span>slice</span><span>(</span><span>1</span><span>,</span> <span>baseState</span><span>.</span><span>length</span><span>)</span><span>,</span>\n<span>]</span><span>;</span>\n<span>// slower 2.5x than Mutative</span>\n<span>// const state = baseState.map((item, index) =&gt;</span>\n<span>// index === 0 ? { ...item, value: i } : item</span>\n<span>// );</span>\n<span>// same performance as Mutative</span>\n<span>// const state = [...baseState];</span>\n<span>// state[0] = { ...baseState[0], value: i };</span></pre></div>\n<blockquote>\n<p>The actual difference depends on which spread operation syntax you use.</p>\n</blockquote>\n<ul>\n<li>Mutative</li>\n</ul>\n<div><pre><span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>[</span><span>0</span><span>]</span><span>.</span><span>value</span> <span>=</span> <span>i</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p><a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/benchmark-array.jpg\"><img src=\"https://github.com/unadlib/mutative/raw/main/benchmark-array.jpg\" alt=\"Mutative vs Reducer benchmark by array\" /></a></p>\n<blockquote>\n<p>Measure(seconds) to update the 1K-100K items array, lower is better(<a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/test/performance/benchmark-array.ts\">view source</a>).</p>\n</blockquote>\n</details>\n<p>Mutative is up to 6x faster than naive handcrafted reducer for updating immutable arrays.</p>\n<p></p><h2>Mutative vs Immer Performance</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#mutative-vs-immer-performance\"></a><p></p>\n<blockquote>\n<p>Mutative passed all of Immer's test cases.</p>\n</blockquote>\n<p>Measure(ops/sec) to update 50K arrays and 1K objects, bigger is better(<a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/test/performance/benchmark.ts\">view source</a>). [Mutative v1.0.11 vs Immer v10.1.1]</p>\n<p><a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/benchmark.jpg\"><img src=\"https://github.com/unadlib/mutative/raw/main/benchmark.jpg\" alt=\"Benchmark\" /></a></p>\n<div><pre><code>Naive handcrafted reducer - No Freeze x 4,469 ops/sec ±0.82% (99 runs sampled)\nMutative - No Freeze x 6,015 ops/sec ±1.17% (94 runs sampled)\nImmer - No Freeze x 5.36 ops/sec ±0.28% (18 runs sampled)\nMutative - Freeze x 959 ops/sec ±0.90% (99 runs sampled)\nImmer - Freeze x 382 ops/sec ±0.53% (94 runs sampled)\nMutative - Patches and No Freeze x 970 ops/sec ±0.99% (96 runs sampled)\nImmer - Patches and No Freeze x 5.22 ops/sec ±0.80% (18 runs sampled)\nMutative - Patches and Freeze x 505 ops/sec ±0.85% (93 runs sampled)\nImmer - Patches and Freeze x 275 ops/sec ±0.49% (89 runs sampled)\nThe fastest method is Mutative - No Freeze\n</code></pre></div>\n<p>Run <code>yarn benchmark</code> to measure performance.</p>\n<blockquote>\n<p>OS: macOS 14.6.1, CPU: Apple M1 Max, Node.js: v20.11.0</p>\n</blockquote>\n<p>Immer relies on auto-freeze to be enabled, if auto-freeze is disabled, Immer will have a huge performance drop and Mutative will have a huge performance lead, especially with large data structures it will have a performance lead of more than 50x.</p>\n<p>So if you are using Immer, you will have to enable auto-freeze for performance. Mutative is disabled auto-freeze by default. With the default configuration of both, we can see the 16x performance gap between Mutative (<code>6,015 ops/sec</code>) and Immer (<code>382 ops/sec</code>).</p>\n<p>Overall, Mutative has a huge performance lead over Immer in <a target=\"_blank\" href=\"https://github.com/unadlib/mutative/tree/main/test/performance\">more performance testing scenarios</a>. Run <code>yarn performance</code> to get all the performance results locally.</p>\n<details>\n<summary><b>More Performance Testing Scenarios, Mutative is up to `2.5X-82.9` faster than Immer: </b></summary>\n<p><a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/test/benchmark/results/all.jpg\"><img src=\"https://github.com/unadlib/mutative/raw/main/test/benchmark/results/all.jpg\" alt=\"Mutative vs Immer - All benchmark results by average multiplier\" /></a></p>\n<blockquote>\n<p><a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/test/benchmark\">view source</a>.</p>\n</blockquote>\n</details>\n<p></p><h2>Features and Benefits</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#features-and-benefits\"></a><p></p>\n<ul>\n<li><strong>Mutation makes immutable updates</strong> - Immutable data structures supporting objects, arrays, Sets and Maps.</li>\n<li><strong>High performance</strong> - 10x faster than immer by default, even faster than naive handcrafted reducer.</li>\n<li><strong>Optional freezing state</strong> - No freezing of immutable data by default.</li>\n<li><strong>Support for JSON Patch</strong> - Full compliance with JSON Patch specification.</li>\n<li><strong>Custom shallow copy</strong> - Support for more types of immutable data.</li>\n<li><strong>Support mark for immutable and mutable data</strong> - Allows for non-invasive marking.</li>\n<li><strong>Safer mutable data access in strict mode</strong> - It brings more secure immutable updates.</li>\n<li><strong>Support for reducer</strong> - Support reducer function and any other immutable state library.</li>\n</ul>\n<p></p><h2>Difference between Mutative and Immer</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#difference-between-mutative-and-immer\"></a><p></p>\n<table>\n<thead>\n<tr>\n<th></th>\n<th>Mutative</th>\n<th>Immer</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Custom shallow copy</td>\n<td>✅</td>\n<td>❌</td>\n</tr>\n<tr>\n<td>Strict mode</td>\n<td>✅</td>\n<td>❌</td>\n</tr>\n<tr>\n<td>No data freeze by default</td>\n<td>✅</td>\n<td>❌</td>\n</tr>\n<tr>\n<td>Non-invasive marking</td>\n<td>✅</td>\n<td>❌</td>\n</tr>\n<tr>\n<td>Complete freeze data</td>\n<td>✅</td>\n<td>❌</td>\n</tr>\n<tr>\n<td>Non-global config</td>\n<td>✅</td>\n<td>❌</td>\n</tr>\n<tr>\n<td>async draft function</td>\n<td>✅</td>\n<td>❌</td>\n</tr>\n<tr>\n<td>Fully compatible with JSON Patch spec</td>\n<td>✅</td>\n<td>❌</td>\n</tr>\n</tbody>\n</table>\n<p>Mutative has fewer bugs such as accidental draft escapes than Immer, <a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/test/immer-non-support.test.ts\">view details</a>.</p>\n<p></p><h2>Installation</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#installation\"></a><p></p>\n<p>Yarn</p>\n<p>NPM</p>\n<p>CDN</p>\n<ul>\n<li>Unpkg: <code>&lt;script src=\"https://unpkg.com/mutative\"&gt;&lt;/script&gt;</code></li>\n<li>JSDelivr: <code>&lt;script src=\"https://cdn.jsdelivr.net/npm/mutative\"&gt;&lt;/script&gt;</code></li>\n</ul>\n<p></p><h2>Usage</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#usage\"></a><p></p>\n<div><pre><span>import</span> <span>{</span> <span>create</span> <span>}</span> <span>from</span> <span>'mutative'</span><span>;</span>\n<span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>foo</span>: <span>'bar'</span><span>,</span>\n <span>list</span>: <span>[</span><span>{</span> <span>text</span>: <span>'coding'</span> <span>}</span><span>]</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>list</span><span>.</span><span>push</span><span>(</span><span>{</span> <span>text</span>: <span>'learning'</span> <span>}</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>state</span><span>)</span><span>.</span><span>not</span><span>.</span><span>toBe</span><span>(</span><span>baseState</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>state</span><span>.</span><span>list</span><span>)</span><span>.</span><span>not</span><span>.</span><span>toBe</span><span>(</span><span>baseState</span><span>.</span><span>list</span><span>)</span><span>;</span></pre></div>\n<p><code>create(baseState, (draft) =&gt; void, options?: Options): newState</code></p>\n<p>The first argument of <code>create()</code> is the base state. Mutative drafts it and passes it to the arguments of the draft function, and performs the draft mutation until the draft function finishes, then Mutative will finalize it and produce the new state.</p>\n<p>Use <code>create()</code> for more advanced features by <a target=\"_blank\" href=\"https://github.com/unadlib/mutative#createstate-fn-options\">setting <code>options</code></a>.</p>\n<p></p><h2>APIs</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#apis\"></a><p></p>\n<ul>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#create\"><code>create()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#apply\"><code>apply()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#current\"><code>current()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#original\"><code>original()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#unsafe\"><code>unsafe()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#isdraft\"><code>isDraft()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#isdraftable\"><code>isDraftable()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#rawreturn\"><code>rawReturn()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#makecreator\"><code>makeCreator()</code></a></li>\n<li><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#marksimpleobject\"><code>markSimpleObject()</code></a></li>\n</ul>\n<p></p><h3><code>create()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#create\"></a><p></p>\n<p>Use <code>create()</code> for draft mutation to get a new state, which also supports currying.</p>\n<div><pre><span>import</span> <span>{</span> <span>create</span> <span>}</span> <span>from</span> <span>'mutative'</span><span>;</span>\n<span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>foo</span>: <span>'bar'</span><span>,</span>\n <span>list</span>: <span>[</span><span>{</span> <span>text</span>: <span>'todo'</span> <span>}</span><span>]</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>foo</span> <span>=</span> <span>'foobar'</span><span>;</span>\n <span>draft</span><span>.</span><span>list</span><span>.</span><span>push</span><span>(</span><span>{</span> <span>text</span>: <span>'learning'</span> <span>}</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p>In this basic example, the changes to the draft are 'mutative' within the draft callback, and <code>create()</code> is finally executed with a new immutable state.</p>\n<p></p><h4><code>create(state, fn, options)</code></h4><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#createstate-fn-options\"></a><p></p>\n<blockquote>\n<p>Then options is optional.</p>\n</blockquote>\n<ul>\n<li>\n<p>strict - <code>boolean</code>, the default is false.</p>\n<blockquote>\n<p>Forbid accessing non-draftable values in strict mode(unless using <a target=\"_blank\" href=\"https://github.com/unadlib/mutative#unsafe\">unsafe()</a>).</p>\n</blockquote>\n<blockquote>\n<p>When strict mode is enabled, mutable data can only be accessed using <a target=\"_blank\" href=\"https://github.com/unadlib/mutative#unsafe\"><code>unsafe()</code></a>.</p>\n</blockquote>\n<blockquote>\n<p><strong>It is recommended to enable <code>strict</code> in development mode and disable <code>strict</code> in production mode.</strong> This will ensure safe explicit returns and also keep good performance in the production build. If the value that does not mix any current draft or is <code>undefined</code> is returned, then use <a target=\"_blank\" href=\"https://github.com/unadlib/mutative#rawreturn\">rawReturn()</a>.</p>\n</blockquote>\n<blockquote>\n<p>If you'd like to enable strict mode by default in a development build and turn it off for production, you can use <code>strict: process.env.NODE_ENV !== 'production'</code>.</p>\n</blockquote>\n</li>\n<li>\n<p>enablePatches - <code>boolean | { pathAsArray?: boolean; arrayLengthAssignment?: boolean; }</code>, the default is false.</p>\n<blockquote>\n<p>Enable patch, and return the patches/inversePatches.</p>\n</blockquote>\n<blockquote>\n<p>If you need to set the shape of the generated patch in more detail, then you can set <code>pathAsArray</code> and <code>arrayLengthAssignment</code>。<code>pathAsArray</code> default value is <code>true</code>, if it's <code>true</code>, the path will be an array, otherwise it is a string; <code>arrayLengthAssignment</code> default value is <code>true</code>, if it's <code>true</code>, the array length will be included in the patches, otherwise no include array length(<strong>NOTE</strong>: If <code>arrayLengthAssignment</code> is <code>false</code>, it is fully compatible with JSON Patch spec, but it may have additional performance loss), <a target=\"_blank\" href=\"https://github.com/unadlib/mutative/issues/6\">view related discussions</a>.</p>\n</blockquote>\n</li>\n<li>\n<p>enableAutoFreeze - <code>boolean</code>, the default is false.</p>\n<blockquote>\n<p>Enable autoFreeze, and return frozen state, and enable circular reference checking only in <code>development</code> mode.</p>\n</blockquote>\n</li>\n<li>\n<p>mark - <code>(target) =&gt; ('mutable'|'immutable'|function) | (target) =&gt; ('mutable'|'immutable'|function)[]</code></p>\n<blockquote>\n<p>Set a mark to determine if the value is mutable or if an instance is an immutable, and it can also return a shallow copy function(<code>AutoFreeze</code> and <code>Patches</code> should both be disabled, Some patches operation might not be equivalent).\nWhen the mark function is (target) =&gt; 'immutable', it means all the objects in the state structure are immutable. In this specific case, you can totally turn on <code>AutoFreeze</code> and <code>Patches</code>.\n<code>mark</code> supports multiple marks, and the marks are executed in order, and the first mark that returns a value will be used.\nWhen a object tree node is marked by the <code>mark</code> function as <code>mutable</code>, all of its child nodes will also not be drafted by Mutative and will retain their original values.</p>\n</blockquote>\n</li>\n</ul>\n<p></p><h4><code>create()</code> - Currying</h4><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#create---currying\"></a><p></p>\n<ul>\n<li>create <code>draft</code></li>\n</ul>\n<div><pre><span>const</span> <span>[</span><span>draft</span><span>,</span> <span>finalize</span><span>]</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>)</span><span>;</span>\n<span>draft</span><span>.</span><span>foobar</span><span>.</span><span>bar</span> <span>=</span> <span>'baz'</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>finalize</span><span>(</span><span>)</span><span>;</span></pre></div>\n<blockquote>\n<p>Support set options such as <code>const [draft, finalize] = create(baseState, { enableAutoFreeze: true });</code></p>\n</blockquote>\n<ul>\n<li>create <code>producer</code></li>\n</ul>\n<div><pre><span>const</span> <span>produce</span> <span>=</span> <span>create</span><span>(</span><span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>foobar</span><span>.</span><span>bar</span> <span>=</span> <span>'baz'</span><span>;</span>\n<span>}</span><span>)</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>produce</span><span>(</span><span>baseState</span><span>)</span><span>;</span></pre></div>\n<blockquote>\n<p>Also support set options such as <code>const produce = create((draft) =&gt; {}, { enableAutoFreeze: true });</code></p>\n</blockquote>\n<p></p><h3><code>apply()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#apply\"></a><p></p>\n<p>Use <code>apply()</code> for applying patches to get the new state.</p>\n<div><pre><span>import</span> <span>{</span> <span>create</span><span>,</span> <span>apply</span> <span>}</span> <span>from</span> <span>'mutative'</span><span>;</span>\n<span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>foo</span>: <span>'bar'</span><span>,</span>\n <span>list</span>: <span>[</span><span>{</span> <span>text</span>: <span>'todo'</span> <span>}</span><span>]</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>[</span><span>state</span><span>,</span> <span>patches</span><span>,</span> <span>inversePatches</span><span>]</span> <span>=</span> <span>create</span><span>(</span>\n <span>baseState</span><span>,</span>\n <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>foo</span> <span>=</span> <span>'foobar'</span><span>;</span>\n <span>draft</span><span>.</span><span>list</span><span>.</span><span>push</span><span>(</span><span>{</span> <span>text</span>: <span>'learning'</span> <span>}</span><span>)</span><span>;</span>\n <span>}</span><span>,</span>\n <span>{</span>\n <span>enablePatches</span>: <span>true</span><span>,</span>\n <span>}</span>\n<span>)</span><span>;</span>\n<span>const</span> <span>nextState</span> <span>=</span> <span>apply</span><span>(</span><span>baseState</span><span>,</span> <span>patches</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>nextState</span><span>)</span><span>.</span><span>toEqual</span><span>(</span><span>state</span><span>)</span><span>;</span>\n<span>const</span> <span>prevState</span> <span>=</span> <span>apply</span><span>(</span><span>state</span><span>,</span> <span>inversePatches</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>prevState</span><span>)</span><span>.</span><span>toEqual</span><span>(</span><span>baseState</span><span>)</span><span>;</span></pre></div>\n<p></p><h3><code>current()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#current\"></a><p></p>\n<p>Get the current value from a draft.</p>\n<ul>\n<li>For any draft where a child node has been modified, the state obtained by executing current() each time will be a new reference object.</li>\n<li>For a draft where no child nodes have been modified, executing current() will always return the original state.</li>\n</ul>\n<blockquote>\n<p>It is recommended to minimize the number of times current() is executed when performing read-only operations, ideally executing it only once.</p>\n</blockquote>\n<div><pre><span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>{</span> <span>a</span>: <span>{</span> <span>b</span>: <span>{</span> <span>c</span>: <span>1</span> <span>}</span> <span>}</span><span>,</span> <span>d</span>: <span>{</span> <span>f</span>: <span>1</span> <span>}</span> <span>}</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>a</span><span>.</span><span>b</span><span>.</span><span>c</span> <span>=</span> <span>2</span><span>;</span>\n <span>expect</span><span>(</span><span>current</span><span>(</span><span>draft</span><span>.</span><span>a</span><span>)</span><span>)</span><span>.</span><span>toEqual</span><span>(</span><span>{</span> <span>b</span>: <span>{</span> <span>c</span>: <span>2</span> <span>}</span> <span>}</span><span>)</span><span>;</span>\n <span>// The node `a` has been modified.</span>\n <span>expect</span><span>(</span><span>current</span><span>(</span><span>draft</span><span>.</span><span>a</span><span>)</span> <span>===</span> <span>current</span><span>(</span><span>draft</span><span>.</span><span>a</span><span>)</span><span>)</span><span>.</span><span>toBeFalsy</span><span>(</span><span>)</span><span>;</span>\n <span>// The node `d` has not been modified.</span>\n <span>expect</span><span>(</span><span>current</span><span>(</span><span>draft</span><span>.</span><span>d</span><span>)</span> <span>===</span> <span>current</span><span>(</span><span>draft</span><span>.</span><span>d</span><span>)</span><span>)</span><span>.</span><span>toBeTruthy</span><span>(</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p></p><h3><code>original()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#original\"></a><p></p>\n<p>Get the original value from a draft.</p>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>foo</span>: <span>'bar'</span><span>,</span>\n <span>list</span>: <span>[</span><span>{</span> <span>text</span>: <span>'todo'</span> <span>}</span><span>]</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>foo</span> <span>=</span> <span>'foobar'</span><span>;</span>\n <span>draft</span><span>.</span><span>list</span><span>.</span><span>push</span><span>(</span><span>{</span> <span>text</span>: <span>'learning'</span> <span>}</span><span>)</span><span>;</span>\n <span>expect</span><span>(</span><span>original</span><span>(</span><span>draft</span><span>.</span><span>list</span><span>)</span><span>)</span><span>.</span><span>toEqual</span><span>(</span><span>[</span><span>{</span> <span>text</span>: <span>'todo'</span> <span>}</span><span>]</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p></p><h3><code>unsafe()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#unsafe\"></a><p></p>\n<p>When strict mode is enabled, mutable data can only be accessed using <code>unsafe()</code>.</p>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>list</span>: <span>[</span><span>]</span><span>,</span>\n <span>date</span>: <span>new</span> <span>Date</span><span>(</span><span>)</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span>\n <span>baseState</span><span>,</span>\n <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>unsafe</span><span>(</span><span>(</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>date</span><span>.</span><span>setFullYear</span><span>(</span><span>2000</span><span>)</span><span>;</span>\n <span>}</span><span>)</span><span>;</span>\n <span>// or return the mutable data:</span>\n <span>// const date = unsafe(() =&gt; draft.date);</span>\n <span>}</span><span>,</span>\n <span>{</span>\n <span>strict</span>: <span>true</span><span>,</span>\n <span>}</span>\n<span>)</span><span>;</span></pre></div>\n<blockquote>\n<p>If you'd like to enable strict mode by default in a development build and turn it off for production, you can use <code>strict: process.env.NODE_ENV !== 'production'</code>.</p>\n</blockquote>\n<p></p><h3><code>isDraft()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#isdraft\"></a><p></p>\n<p>Check if a value is a draft.</p>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>date</span>: <span>new</span> <span>Date</span><span>(</span><span>)</span><span>,</span>\n <span>list</span>: <span>[</span><span>{</span> <span>text</span>: <span>'todo'</span> <span>}</span><span>]</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>expect</span><span>(</span><span>isDraft</span><span>(</span><span>draft</span><span>.</span><span>date</span><span>)</span><span>)</span><span>.</span><span>toBeFalsy</span><span>(</span><span>)</span><span>;</span>\n <span>expect</span><span>(</span><span>isDraft</span><span>(</span><span>draft</span><span>.</span><span>list</span><span>)</span><span>)</span><span>.</span><span>toBeTruthy</span><span>(</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p></p><h3><code>isDraftable()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#isdraftable\"></a><p></p>\n<p>Check if a value is draftable</p>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>date</span>: <span>new</span> <span>Date</span><span>(</span><span>)</span><span>,</span>\n <span>list</span>: <span>[</span><span>{</span> <span>text</span>: <span>'todo'</span> <span>}</span><span>]</span><span>,</span>\n<span>}</span><span>;</span>\n<span>expect</span><span>(</span><span>isDraftable</span><span>(</span><span>baseState</span><span>.</span><span>date</span><span>)</span><span>)</span><span>.</span><span>toBeFalsy</span><span>(</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>isDraftable</span><span>(</span><span>baseState</span><span>.</span><span>list</span><span>)</span><span>)</span><span>.</span><span>toBeTruthy</span><span>(</span><span>)</span><span>;</span></pre></div>\n<blockquote>\n<p>You can set a mark to determine if the value is draftable, and the mark function should be the same as passing in <code>create()</code> mark option.</p>\n</blockquote>\n<p></p><h3><code>rawReturn()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#rawreturn\"></a><p></p>\n<p>For return values that do not contain any drafts, you can use <code>rawReturn()</code> to wrap this return value to improve performance. It ensure that the return value is only returned explicitly.</p>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span> <span>id</span>: <span>'test'</span> <span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span> <span>as</span> <span>{</span> <span>id</span>: <span>string</span> <span>}</span> <span>|</span> <span>undefined</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>return</span> <span>rawReturn</span><span>(</span><span>undefined</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>state</span><span>)</span><span>.</span><span>toBe</span><span>(</span><span>undefined</span><span>)</span><span>;</span></pre></div>\n<blockquote>\n<p>If the return value mixes drafts, you should not use <code>rawReturn()</code>.</p>\n</blockquote>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span> <span>a</span>: <span>1</span><span>,</span> <span>b</span>: <span>{</span> <span>c</span>: <span>1</span> <span>}</span> <span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>if</span> <span>(</span><span>draft</span><span>.</span><span>b</span><span>.</span><span>c</span> <span>===</span> <span>1</span><span>)</span> <span>{</span>\n <span>return</span> <span>{</span>\n ...<span>draft</span><span>,</span>\n <span>a</span>: <span>2</span><span>,</span>\n <span>}</span><span>;</span>\n <span>}</span>\n<span>}</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>state</span><span>)</span><span>.</span><span>toEqual</span><span>(</span><span>{</span> <span>a</span>: <span>2</span><span>,</span> <span>b</span>: <span>{</span> <span>c</span>: <span>1</span> <span>}</span> <span>}</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>isDraft</span><span>(</span><span>state</span><span>.</span><span>b</span><span>)</span><span>)</span><span>.</span><span>toBeFalsy</span><span>(</span><span>)</span><span>;</span></pre></div>\n<p>If you use <code>rawReturn()</code>, we recommend that you enable <code>strict</code> mode in development.</p>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span> <span>a</span>: <span>1</span><span>,</span> <span>b</span>: <span>{</span> <span>c</span>: <span>1</span> <span>}</span> <span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span>\n <span>baseState</span><span>,</span>\n <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>if</span> <span>(</span><span>draft</span><span>.</span><span>b</span><span>.</span><span>c</span> <span>===</span> <span>1</span><span>)</span> <span>{</span>\n <span>return</span> <span>rawReturn</span><span>(</span><span>{</span>\n ...<span>draft</span><span>,</span>\n <span>a</span>: <span>2</span><span>,</span>\n <span>}</span><span>)</span><span>;</span>\n <span>}</span>\n <span>}</span><span>,</span>\n <span>{</span>\n <span>strict</span>: <span>true</span><span>,</span>\n <span>}</span>\n<span>)</span><span>;</span>\n<span>// it will warn `The return value contains drafts, please don't use 'rawReturn()' to wrap the return value.` in strict mode.</span>\n<span>expect</span><span>(</span><span>state</span><span>)</span><span>.</span><span>toEqual</span><span>(</span><span>{</span> <span>a</span>: <span>2</span><span>,</span> <span>b</span>: <span>{</span> <span>c</span>: <span>1</span> <span>}</span> <span>}</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>isDraft</span><span>(</span><span>state</span><span>.</span><span>b</span><span>)</span><span>)</span><span>.</span><span>toBeFalsy</span><span>(</span><span>)</span><span>;</span></pre></div>\n<p></p><h3><code>makeCreator()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#makecreator\"></a><p></p>\n<p><code>makeCreator()</code> only takes <a target=\"_blank\" href=\"https://github.com/unadlib/mutative#createstate-fn-options\">options</a> as the first argument, resulting in a custom <code>create()</code> function.</p>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>foo</span>: <span>{</span>\n <span>bar</span>: <span>'str'</span><span>,</span>\n <span>}</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>create</span> <span>=</span> <span>makeCreator</span><span>(</span><span>{</span>\n <span>enablePatches</span>: <span>true</span><span>,</span>\n<span>}</span><span>)</span><span>;</span>\n<span>const</span> <span>[</span><span>state</span><span>,</span> <span>patches</span><span>,</span> <span>inversePatches</span><span>]</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>foo</span><span>.</span><span>bar</span> <span>=</span> <span>'new str'</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p></p><h3><code>markSimpleObject()</code></h3><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#marksimpleobject\"></a><p></p>\n<p><code>markSimpleObject()</code> is a mark function that marks all objects as immutable.</p>\n<div><pre><span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>foo</span>: <span>{</span>\n <span>bar</span>: <span>'str'</span><span>,</span>\n <span>}</span><span>,</span>\n <span>simpleObject</span>: <span>Object</span><span>.</span><span>create</span><span>(</span><span>null</span><span>)</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>create</span><span>(</span>\n <span>baseState</span><span>,</span>\n <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>foo</span><span>.</span><span>bar</span> <span>=</span> <span>'new str'</span><span>;</span>\n <span>draft</span><span>.</span><span>simpleObject</span><span>.</span><span>a</span> <span>=</span> <span>'a'</span><span>;</span>\n <span>}</span><span>,</span>\n <span>{</span>\n <span>mark</span>: <span>markSimpleObject</span><span>,</span>\n <span>}</span>\n<span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>state</span><span>.</span><span>simpleObject</span><span>)</span><span>.</span><span>not</span><span>.</span><span>toBe</span><span>(</span><span>baseState</span><span>.</span><span>simpleObject</span><span>)</span><span>;</span></pre></div>\n<p><a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/docs/README.md\">View more API docs</a>.</p>\n<p></p><h2>Using TypeScript</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#using-typescript\"></a><p></p>\n<ul>\n<li><code>castDraft()</code></li>\n<li><code>castImmutable()</code></li>\n<li><code>Draft&lt;T&gt;</code></li>\n<li><code>Immutable&lt;T&gt;</code></li>\n<li><code>Patches</code></li>\n<li><code>Patch</code></li>\n<li><code>Options&lt;O, F&gt;</code></li>\n</ul>\n<p></p><h2>Integration with React</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#integration-with-react\"></a><p></p>\n<ul>\n<li><a target=\"_blank\" href=\"https://github.com/mutativejs/use-mutative\">use-mutative</a> - A 2-6x faster alternative to useState with spread operation</li>\n<li><a target=\"_blank\" href=\"https://github.com/mutativejs/use-travel\">use-travel</a> - A React hook for state time travel with undo, redo, reset and archive functionalities.</li>\n<li><a target=\"_blank\" href=\"https://github.com/mutativejs/zustand-mutative\">zustand-mutative</a> - A Mutative middleware for Zustand enhances the efficiency of immutable state updates.</li>\n</ul>\n<p></p><h2>FAQs</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#faqs\"></a><p></p>\n<ul>\n<li>I'm already using Immer, can I migrate smoothly to Mutative?</li>\n</ul>\n<p>Yes. Unless you have to be compatible with Internet Explorer, Mutative supports almost all of Immer features, and you can easily migrate from Immer to Mutative.</p>\n<blockquote>\n<p>Migration is also not possible for React Native that does not support Proxy. React Native uses a new JS engine during refactoring - Hermes, and it (if &lt; v0.59 or when using the Hermes engine on React Native &lt; v0.64) does <a target=\"_blank\" href=\"https://github.com/facebook/hermes/issues/33\">not support Proxy on Android</a>, but <a target=\"_blank\" href=\"https://reactnative.dev/blog/2021/03/12/version-0.64#hermes-with-proxy-support\">React Native v0.64 with the Hermes engine support Proxy</a>.</p>\n</blockquote>\n<ul>\n<li>Can Mutative be integrated with Redux?</li>\n</ul>\n<p>Yes. Mutative supports return values for reducer, and <code>redux-toolkit</code> is considering support for <a target=\"_blank\" href=\"https://github.com/reduxjs/redux-toolkit/pull/3074\">configurable <code>produce()</code></a>.</p>\n<p></p><h2>Migration from Immer to Mutative</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#migration-from-immer-to-mutative\"></a><p></p>\n<blockquote>\n<p><a target=\"_blank\" href=\"https://github.com/exuanbo/mutative-compat\">mutative-compat</a> - Mutative wrapper with full Immer API compatibility, you can use it to quickly migrate from Immer to Mutative.</p>\n</blockquote>\n<ol>\n<li><code>produce()</code> -&gt; <code>create()</code></li>\n</ol>\n<p>Mutative auto freezing option is disabled by default, Immer auto freezing option is enabled by default (if disabled, Immer performance will have a more huge drop).</p>\n<blockquote>\n<p>You need to check if auto freezing has any impact on your project. If it depends on auto freezing, you can enable it yourself in Mutative.</p>\n</blockquote>\n<div><pre><span>import</span> <span>produce</span> <span>from</span> <span>'immer'</span><span>;</span>\n<span>const</span> <span>nextState</span> <span>=</span> <span>produce</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>[</span><span>1</span><span>]</span><span>.</span><span>done</span> <span>=</span> <span>true</span><span>;</span>\n <span>draft</span><span>.</span><span>push</span><span>(</span><span>{</span> <span>title</span>: <span>'something'</span> <span>}</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p>Use Mutative</p>\n<div><pre><span>import</span> <span>{</span> <span>create</span> <span>}</span> <span>from</span> <span>'mutative'</span><span>;</span>\n<span>const</span> <span>nextState</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>[</span><span>1</span><span>]</span><span>.</span><span>done</span> <span>=</span> <span>true</span><span>;</span>\n <span>draft</span><span>.</span><span>push</span><span>(</span><span>{</span> <span>title</span>: <span>'something'</span> <span>}</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<ol>\n<li><code>Patches</code></li>\n</ol>\n<div><pre><span>import</span> <span>{</span> <span>produceWithPatches</span><span>,</span> <span>applyPatches</span> <span>}</span> <span>from</span> <span>'immer'</span><span>;</span>\n<span>enablePatches</span><span>(</span><span>)</span><span>;</span>\n<span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>age</span>: <span>33</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>[</span><span>nextState</span><span>,</span> <span>patches</span><span>,</span> <span>inversePatches</span><span>]</span> <span>=</span> <span>produceWithPatches</span><span>(</span>\n <span>baseState</span><span>,</span>\n <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>age</span><span>++</span><span>;</span>\n <span>}</span>\n<span>)</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>applyPatches</span><span>(</span><span>nextState</span><span>,</span> <span>inversePatches</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>state</span><span>)</span><span>.</span><span>toEqual</span><span>(</span><span>baseState</span><span>)</span><span>;</span></pre></div>\n<p>Use Mutative</p>\n<div><pre><span>import</span> <span>{</span> <span>create</span><span>,</span> <span>apply</span> <span>}</span> <span>from</span> <span>'mutative'</span><span>;</span>\n<span>const</span> <span>baseState</span> <span>=</span> <span>{</span>\n <span>age</span>: <span>33</span><span>,</span>\n<span>}</span><span>;</span>\n<span>const</span> <span>[</span><span>nextState</span><span>,</span> <span>patches</span><span>,</span> <span>inversePatches</span><span>]</span> <span>=</span> <span>create</span><span>(</span>\n <span>baseState</span><span>,</span>\n <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>draft</span><span>.</span><span>age</span><span>++</span><span>;</span>\n <span>}</span><span>,</span>\n <span>{</span>\n <span>enablePatches</span>: <span>true</span><span>,</span>\n <span>}</span>\n<span>)</span><span>;</span>\n<span>const</span> <span>state</span> <span>=</span> <span>apply</span><span>(</span><span>nextState</span><span>,</span> <span>inversePatches</span><span>)</span><span>;</span>\n<span>expect</span><span>(</span><span>state</span><span>)</span><span>.</span><span>toEqual</span><span>(</span><span>baseState</span><span>)</span><span>;</span></pre></div>\n<ol>\n<li>Return <code>undefined</code></li>\n</ol>\n<div><pre><span>import</span> <span>produce</span><span>,</span> <span>{</span> <span>nothing</span> <span>}</span> <span>from</span> <span>'immer'</span><span>;</span>\n<span>const</span> <span>nextState</span> <span>=</span> <span>produce</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>return</span> <span>nothing</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p>Use Mutative</p>\n<div><pre><span>import</span> <span>{</span> <span>create</span><span>,</span> <span>rawReturn</span> <span>}</span> <span>from</span> <span>'mutative'</span><span>;</span>\n<span>const</span> <span>nextState</span> <span>=</span> <span>create</span><span>(</span><span>baseState</span><span>,</span> <span>(</span><span>draft</span><span>)</span> <span>=&gt;</span> <span>{</span>\n <span>return</span> <span>rawReturn</span><span>(</span><span>undefined</span><span>)</span><span>;</span>\n<span>}</span><span>)</span><span>;</span></pre></div>\n<p></p><h2>Contributing</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#contributing\"></a><p></p>\n<p>Mutative goal is to provide efficient and immutable updates. The focus is on performance improvements and providing better APIs for better development experiences. We are still working on it and welcome PRs that may help Mutative.</p>\n<p>Development Workflow:</p>\n<ul>\n<li>Clone Mutative repo.</li>\n<li>Run <code>yarn install</code> to install all the dependencies.</li>\n<li>Run <code>yarn prettier</code> to format the code.</li>\n<li><code>yarn test --watch</code> runs an interactive test watcher.</li>\n<li>Run <code>yarn commit</code> to make a git commit.</li>\n</ul>\n<p></p><h2>License</h2><a target=\"_blank\" href=\"https://github.com/unadlib/mutative#license\"></a><p></p>\n<p>Mutative is <a target=\"_blank\" href=\"https://github.com/unadlib/mutative/blob/main/LICENSE\">MIT licensed</a>.</p>\n</article></div>",
"author": "",
"favicon": "https://github.githubassets.com/favicons/favicon.svg",
"source": "github.com",
"published": "",
"ttr": 519,
"type": "object"
}