Created
July 11, 2024 19:25
-
-
Save esshka/0b03a078e62df8feacee52e6364729fe to your computer and use it in GitHub Desktop.
rehuy
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 ctx = []; | |
function addEffect(current, effects) { | |
effects.add(current); | |
current.deps.add(effects); | |
} | |
function createAtom(value) { | |
const effects = new Set(); | |
const getState = () => { | |
const current = ctx[ctx.length - 1]; | |
if (current) addEffect(current, effects); | |
return value; | |
}; | |
const update = (nextValue) => { | |
value = nextValue; | |
for (const sub of [...effects]) { | |
sub.execute(); | |
} | |
}; | |
return { getState, update }; | |
} | |
function cleanup(current) { | |
for (const dep of current.deps) { | |
dep.delete(current); | |
} | |
current.deps.clear(); | |
} | |
function createEffect(fn) { | |
const execute = () => { | |
cleanup(current); | |
ctx.push(current); | |
try { | |
fn(); | |
} finally { | |
ctx.pop(); | |
} | |
}; | |
const current = { | |
deps: new Set(), | |
execute | |
}; | |
execute(); | |
} | |
const atom = createAtom(5); | |
console.log(ctx); | |
createEffect(() => console.log(atom.getState())); | |
atom.update(10); | |
atom.update(5); | |
atom.update(11); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment