Skip to content

Commit 33a305b

Browse files
authored
fix: Clearing empty Set&Map should be noop (#682). Fixes #680
1 parent c9e7116 commit 33a305b

File tree

2 files changed

+28
-10
lines changed

2 files changed

+28
-10
lines changed

__tests__/map-set.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,5 +266,19 @@ function runBaseTest(name, useProxies, autoFreeze, useListener) {
266266
]
267267
])
268268
})
269+
270+
test("#680 - Clearing empty Set&Map should be noop", () => {
271+
const map = new Map()
272+
let result = produce(map, draft => {
273+
draft.clear()
274+
})
275+
expect(result).toBe(map)
276+
277+
const set = new Set()
278+
result = produce(set, draft => {
279+
draft.clear()
280+
})
281+
expect(result).toBe(set)
282+
})
269283
})
270284
}

src/plugins/mapset.ts

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -108,13 +108,15 @@ export function enableMapSet() {
108108
p.clear = function() {
109109
const state: MapState = this[DRAFT_STATE]
110110
assertUnrevoked(state)
111-
prepareMapCopy(state)
112-
markChanged(state)
113-
state.assigned_ = new Map()
114-
each(state.base_, key => {
115-
state.assigned_!.set(key, false)
116-
})
117-
return state.copy_!.clear()
111+
if (latest(state).size) {
112+
prepareMapCopy(state)
113+
markChanged(state)
114+
state.assigned_ = new Map()
115+
each(state.base_, key => {
116+
state.assigned_!.set(key, false)
117+
})
118+
state.copy_!.clear()
119+
}
118120
}
119121

120122
p.forEach = function(
@@ -273,9 +275,11 @@ export function enableMapSet() {
273275
p.clear = function() {
274276
const state: SetState = this[DRAFT_STATE]
275277
assertUnrevoked(state)
276-
prepareSetCopy(state)
277-
markChanged(state)
278-
return state.copy_!.clear()
278+
if (latest(state).size) {
279+
prepareSetCopy(state)
280+
markChanged(state)
281+
state.copy_!.clear()
282+
}
279283
}
280284

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

0 commit comments

Comments
 (0)