Skip to content

Commit

Permalink
fix: Append to array when key is "-" (#872)
Browse files Browse the repository at this point in the history
* Appends to array when key is "-"

* Avoids unnecessary copy of patches in applyPatches
  • Loading branch information
lourd committed Nov 24, 2021
1 parent 2794576 commit 2afdb1b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
16 changes: 16 additions & 0 deletions __tests__/patch.js
Expand Up @@ -720,6 +720,22 @@ describe("arrays - delete", () => {
)
})

describe("arrays - append", () => {
test("appends to array when last part of path is '-'", () => {
const state = {
list: [1, 2, 3]
}
const patch = {
op: "add",
value: 4,
path: ["list", "-"]
}
expect(applyPatches(state, [patch])).toEqual({
list: [1, 2, 3, 4]
})
})
})

describe("sets - add - 1", () => {
runPatchTest(
new Set([1]),
Expand Down
11 changes: 8 additions & 3 deletions src/core/immerClass.ts
Expand Up @@ -196,16 +196,21 @@ export class Immer implements ProducersFns {
break
}
}
// If there was a patch that replaced the entire state, start from the
// patch after that.
if (i > -1) {
patches = patches.slice(i + 1)
}

const applyPatchesImpl = getPlugin("Patches").applyPatches_
if (isDraft(base)) {
// N.B: never hits if some patch a replacement, patches are never drafts
return applyPatchesImpl(base, patches) as any
return applyPatchesImpl(base, patches)
}
// Otherwise, produce a copy of the base state.
return this.produce(base, (draft: Drafted) =>
applyPatchesImpl(draft, patches.slice(i + 1))
) as any
applyPatchesImpl(draft, patches)
)
}
}

Expand Down
4 changes: 3 additions & 1 deletion src/plugins/patches.ts
Expand Up @@ -240,7 +240,9 @@ export function enablePatches() {
case ADD:
switch (type) {
case Archtype.Array:
return base.splice(key as any, 0, value)
return key === "-"
? base.push(value)
: base.splice(key as any, 0, value)
case Archtype.Map:
return base.set(key, value)
case Archtype.Set:
Expand Down

0 comments on commit 2afdb1b

Please sign in to comment.