Skip to content

Instantly share code, notes, and snippets.

@esshka
Created July 11, 2024 19:25
Show Gist options
  • Save esshka/0b03a078e62df8feacee52e6364729fe to your computer and use it in GitHub Desktop.
Save esshka/0b03a078e62df8feacee52e6364729fe to your computer and use it in GitHub Desktop.
rehuy
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