Last active
July 27, 2025 10:15
-
-
Save clinuxrulz/d98b2b8bb2d63163f6b079a04ecca779 to your computer and use it in GitHub Desktop.
O(1) glitch free createSelector in solidjs user space
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://playground.solidjs.com/anonymous/7ccf3971-2a47-45d5-82ed-1bc3a0481637 | |
import { render } from "solid-js/web"; | |
import { type Accessor, createSignal, createMemo, type Signal, onCleanup, untrack, For } from "solid-js"; | |
function createSelector(a: Accessor<string | undefined>): (k: string) => boolean { | |
let map = new Map<string,{ | |
s: Signal<boolean>, | |
refCount: number, | |
}>(); | |
let lastSelected = untrack(a); | |
let b = createMemo( | |
() => { | |
let a2 = a(); | |
if (lastSelected != undefined) { | |
let s = map.get(lastSelected); | |
if (s != undefined) { | |
s.s[1](false); | |
} | |
} | |
if (a2 != undefined) { | |
let s = map.get(a2); | |
if (s != undefined) { | |
s.s[1](true); | |
} | |
} | |
lastSelected = a2; | |
return a2; | |
}, | |
undefined, | |
{ | |
equals: () => true, | |
} | |
); | |
return (k) => { | |
let _forceUpdateOrder = b(); | |
onCleanup(() => { | |
let s = map.get(k); | |
if (s != undefined) { | |
s.refCount--; | |
if (s.refCount == 0) { | |
queueMicrotask(() => { | |
if (s.refCount == 0) { | |
map.delete(k); | |
} | |
}); | |
} | |
} | |
}); | |
if (map.has(k)) { | |
let s = map.get(k)!; | |
s.refCount++; | |
return s.s[0](); | |
} | |
let selected = untrack(() => a() == k); | |
let signal = createSignal(selected); | |
map.set(k, { | |
s: signal, | |
refCount: 1, | |
}); | |
return signal[0](); | |
}; | |
} | |
function Counter() { | |
let [ selectedKey, setSelectedKey ] = createSignal<string>("B"); | |
let isSelected = createSelector(selectedKey); | |
return ( | |
<For each={Array(10).fill(undefined).map((_,idx) => String.fromCharCode('A'.charCodeAt(0) + idx))}> | |
{(key) => ( | |
<> | |
<button | |
onClick={() => | |
setSelectedKey(key) | |
} | |
style={{ | |
"background-color": isSelected(key) ? "green" : "grey" | |
}} | |
> | |
{key} | |
</button> | |
<br/> | |
</> | |
)} | |
</For> | |
); | |
} | |
render(() => <Counter />, document.getElementById("app")!); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment