Created
January 26, 2024 06:22
-
-
Save sapjax/56a98790c1742af35fb29d5be9361790 to your computer and use it in GitHub Desktop.
signal
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
const context = []; | |
function subscribe(running, subscriptions) { | |
subscriptions.add(running); | |
running.dependencies.add(subscriptions); | |
} | |
export function createSignal(value) { | |
const subscriptions = new Set(); | |
const read = () => { | |
const running = context[context.length - 1]; | |
if (running) subscribe(running, subscriptions); | |
return value; | |
}; | |
const write = (nextValue) => { | |
value = nextValue; | |
for (const sub of [...subscriptions]) { | |
sub.execute(); | |
} | |
}; | |
return [read, write]; | |
} | |
function cleanup(running) { | |
for (const dep of running.dependencies) { | |
dep.delete(running); | |
} | |
running.dependencies.clear(); | |
} | |
export function createEffect(fn) { | |
const execute = () => { | |
cleanup(running); | |
context.push(running); | |
try { | |
fn(); | |
} finally { | |
context.pop(); | |
} | |
}; | |
const running = { | |
execute, | |
dependencies: new Set() | |
}; | |
execute(); | |
} | |
export function createMemo(fn) { | |
const [s, set] = createSignal(); | |
createEffect(() => set(fn())); | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment