Skip to content

Commit

Permalink
fix: Clearing empty Set&Map should be noop (#682). Fixes #680
Browse files Browse the repository at this point in the history
  • Loading branch information
nifgraup committed Oct 20, 2020
1 parent c9e7116 commit 33a305b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
14 changes: 14 additions & 0 deletions __tests__/map-set.js
Expand Up @@ -266,5 +266,19 @@ function runBaseTest(name, useProxies, autoFreeze, useListener) {
]
])
})

test("#680 - Clearing empty Set&Map should be noop", () => {
const map = new Map()
let result = produce(map, draft => {
draft.clear()
})
expect(result).toBe(map)

const set = new Set()
result = produce(set, draft => {
draft.clear()
})
expect(result).toBe(set)
})
})
}
24 changes: 14 additions & 10 deletions src/plugins/mapset.ts
Expand Up @@ -108,13 +108,15 @@ export function enableMapSet() {
p.clear = function() {
const state: MapState = this[DRAFT_STATE]
assertUnrevoked(state)
prepareMapCopy(state)
markChanged(state)
state.assigned_ = new Map()
each(state.base_, key => {
state.assigned_!.set(key, false)
})
return state.copy_!.clear()
if (latest(state).size) {
prepareMapCopy(state)
markChanged(state)
state.assigned_ = new Map()
each(state.base_, key => {
state.assigned_!.set(key, false)
})
state.copy_!.clear()
}
}

p.forEach = function(
Expand Down Expand Up @@ -273,9 +275,11 @@ export function enableMapSet() {
p.clear = function() {
const state: SetState = this[DRAFT_STATE]
assertUnrevoked(state)
prepareSetCopy(state)
markChanged(state)
return state.copy_!.clear()
if (latest(state).size) {
prepareSetCopy(state)
markChanged(state)
state.copy_!.clear()
}
}

p.values = function(): IterableIterator<any> {
Expand Down

0 comments on commit 33a305b

Please sign in to comment.