Skip to content

Instantly share code, notes, and snippets.

@kevinfiol
Created September 11, 2023 15:07
Show Gist options
  • Save kevinfiol/0a1e88411ed66f76e46ba8f8fdfb96a6 to your computer and use it in GitHub Desktop.
Save kevinfiol/0a1e88411ed66f76e46ba8f8fdfb96a6 to your computer and use it in GitHub Desktop.
vyce but with a getter setter api
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);
@kevinfiol
Copy link
Author

let comps = [],
  isFn = x => typeof x === 'function';

class Store {
  constructor(init) {
    this._value = init;
    this.subs = [];
  }
  
  get value() {
    let comp = comps[comps.length - 1];
    if (comp) this.sub(comp, false);
    return this._value;
  }
  
  set value(v) {
    this._value = v;
    for (let sub of this.subs) sub(v);
  }
  
  sub(fn, run = true) {
    let subs = this.subs;
    if (run) fn(this._value);
    if (!~subs.indexOf(fn)) subs.push(fn);
    return idx =>
      (~(idx = subs.indexOf(fn))) && subs.splice(idx, 1);
  }
  
  end() {
    this.subs = [];
  }
}

const store = init => new Store(init);

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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment