Skip to content

Commit c39d701

Browse files
tomohiro86Tomohiro Yamada
andauthored
fix: guard against double-unsubscribe removing wrong subscriber in cache.ts (#4252)
fix: guard against double-unsubscribe removing wrong subscriber When the unsubscribe function returned by `subscribe` was called more than once, `subs.indexOf(callback)` returned -1, causing `subs.splice(-1, 1)` to silently remove the last subscriber in the array instead of doing nothing. Fix by checking `index >= 0` before mutating the array, using the same O(1) swap-and-pop pattern already used in `subscribe-key.ts`. Signed-off-by: tomohiro86 <supersonic.dps@gmail.com> Co-authored-by: Tomohiro Yamada <tomohiro.yamada@TomohironoMacBook-Air.local>
1 parent 46f3954 commit c39d701

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

src/_internal/utils/cache.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,14 @@ export const initCache = <Data = any>(
5656
subscriptions[key] = subs
5757

5858
subs.push(callback)
59-
return () => subs.splice(subs.indexOf(callback), 1)
59+
return () => {
60+
const index = subs.indexOf(callback)
61+
if (index >= 0) {
62+
// O(1): swap with the last element and pop
63+
subs[index] = subs[subs.length - 1]
64+
subs.pop()
65+
}
66+
}
6067
}
6168
const setter = (key: string, value: any, prev: any) => {
6269
provider.set(key, value)

0 commit comments

Comments
 (0)