From 038b60f7980b636e1fb82b16a3d768beb07a9973 Mon Sep 17 00:00:00 2001 From: unadlib Date: Sun, 16 Jun 2024 14:00:09 +0800 Subject: [PATCH] docs(readme): update --- README.md | 21 ++++++++++++--------- test/current.test.ts | 21 ++++++++++++++++++++- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3069433..16fc43e 100644 --- a/README.md +++ b/README.md @@ -334,16 +334,19 @@ expect(prevState).toEqual(baseState); Get the current value from a draft. -```ts -const baseState = { - foo: 'bar', - list: [{ text: 'todo' }], -}; +- 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. -const state = create(baseState, (draft) => { - draft.foo = 'foobar'; - draft.list.push({ text: 'learning' }); - expect(current(draft.list)).toEqual([{ text: 'todo' }, { text: 'learning' }]); +> It is recommended to minimize the number of times current() is executed when performing read-only operations, ideally executing it only once. + +```ts +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(); }); ``` diff --git a/test/current.test.ts b/test/current.test.ts index cdffdfc..631d447 100644 --- a/test/current.test.ts +++ b/test/current.test.ts @@ -5,6 +5,16 @@ import { create, current, isDraft } from '../src'; describe('current', () => { + test('base', () => { + 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(); + }); + }); test('should return the current value', () => { interface Item { foo: string; @@ -141,6 +151,9 @@ test('nested draft', () => { d: number; }; }>; + j: { + k: number; + }; }; const baseState: State = { c: { @@ -167,6 +180,9 @@ test('nested draft', () => { }, }, ]), + j: { + k: 1, + }, }; create(baseState, (draft) => { draft.c.a = 2; @@ -191,7 +207,6 @@ test('nested draft', () => { }, }, }; - const d = current(draft.d); const map = current(draft.map); const set = current(draft.set); @@ -202,5 +217,9 @@ test('nested draft', () => { const f = set.values().next().value.d.d.f.f.f; expect(f).toEqual({ a: 2 }); expect(isDraft(f)).toBeFalsy(); + // the node `d` has been changed + expect(current(draft.d) === current(draft.d)).toBeFalsy(); + // the node `j` has not been changed + expect(current(draft.j) === current(draft.j)).toBeTruthy(); }); });