https://github.com/mutativejs/mutability
A JavaScript library for transactional mutable updates
https://github.com/mutativejs/mutability
immutability mutative transactional
Last synced: 10 months ago
JSON representation
A JavaScript library for transactional mutable updates
- Host: GitHub
- URL: https://github.com/mutativejs/mutability
- Owner: mutativejs
- License: mit
- Created: 2024-02-23T16:29:15.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-11-23T17:22:36.000Z (over 1 year ago)
- Last Synced: 2024-12-11T05:51:33.878Z (over 1 year ago)
- Topics: immutability, mutative, transactional
- Language: TypeScript
- Homepage:
- Size: 630 KB
- Stars: 37
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# mutability

[](http://badge.fury.io/js/mutability)

A JavaScript library for transactional mutable updates based on [Mutative](https://github.com/unadlib/mutative).
## Motivation
When we want to perform transactional updates on a mutable object, if an error is caught during the update process, the mutable update will not be applied at all. Otherwise, the mutable update will be applied to the mutable object. Therefore, we need a tool to implement this functionality.
## Installation
```sh
yarn add mutative mutability
```
or with npm
```sh
npm install mutative mutability
```
## Usage
```ts
import { mutate } from 'mutability';
test('base - mutate', () => {
const baseState = {
a: {
c: 1,
},
};
const { patches, inversePatches } = mutate(baseState, (draft) => {
draft.a.c = 2;
});
expect(baseState).toEqual({ a: { c: 2 } });
expect({ patches, inversePatches }).toEqual({
patches: [
{
op: 'replace',
path: ['a', 'c'],
value: 2,
},
],
inversePatches: [
{
op: 'replace',
path: ['a', 'c'],
value: 1,
},
],
});
apply(baseState, inversePatches);
expect(baseState).toEqual({ a: { c: 1 } });
});
test('base - mutate with error', () => {
const baseState = {
a: {
c: 1,
},
b: {
c: 1,
},
};
try {
mutate(baseState, (draft) => {
draft.a.c = 2;
throw new Error('error');
draft.b.c = 2;
});
} catch (e) {
//
}
expect(baseState).toEqual({
a: {
c: 1,
},
b: {
c: 1,
},
});
});
```
## APIs
### `mutate()`
Mutate the mutable object, and return the patches and inverse patches.
### `apply()`
Apply the mutable update with patches.
## License
Mutability is [MIT licensed](https://github.com/mutativejs/mutability/blob/main/LICENSE).