Created
September 11, 2023 15:07
-
-
Save kevinfiol/0a1e88411ed66f76e46ba8f8fdfb96a6 to your computer and use it in GitHub Desktop.
vyce but with a getter setter api
This file contains 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
let comps = [], | |
isFn = x => typeof x === 'function'; | |
function store(init) { | |
let $, | |
x = init, | |
subs = []; | |
return $ = { | |
get value() { | |
let comp = comps[comps.length - 1]; | |
if (comp) $.sub(comp, false); | |
return x; | |
}, | |
set value(v) { | |
x = v; | |
for (let sub of subs) sub(x); | |
}, | |
sub(fn, run = true) { | |
if (run) fn(x); | |
if (!~subs.indexOf(fn)) subs.push(fn); | |
return idx => | |
(~(idx = subs.indexOf(fn))) && subs.splice(idx, 1); | |
}, | |
end: _ => subs = [] | |
}; | |
} | |
function computed(fn) { | |
let comb = store(), | |
calc = _ => { | |
if (~comps.indexOf(calc)) | |
throw Error('Circular Dependency'); | |
comps.push(calc); | |
comb.value = fn(); | |
comps.pop(); | |
} | |
calc(); | |
return comb; | |
} | |
const authors = store([ | |
{ name: 'haruki', age: 25 }, | |
{ name: 'james', age: 32 }, | |
{ name: 'agatha', age: 62 } | |
]); | |
const youngAuthors = computed(() => | |
authors.value.filter(author => author.age < 40) | |
); | |
console.log(youngAuthors.value); | |
authors.value = [ | |
...authors.value, | |
{ name: 'david', age: 28 }, | |
{ name: 'lovecraft', age: 57 } | |
]; | |
console.log(youngAuthors.value); |
Author
kevinfiol
commented
Sep 12, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment