a := 1;
b := 2;
c := a + b; //c === 3
a := 3; //c === 5
let ReactiveDeps = {
funcs: new Map(),
vars: new Map(),
activeID: null
};
function Merge(fn, args) {
...
function obsFunc() {
ReactiveDeps.activeID = _id;
let res = fn.apply(this, args);
ReactiveDeps.activeID = null;
return res;
};
...
}
function Merge(fn, args) {
...
stream = new Stream(obsFunc())
ReactiveDeps.funcs.set(_id, function() {
stream.set(obsFunc());
});
return stream;
}
let Stream = class {
...
get() {
let activeID = ReactiveDeps.activeID
if (activeID) {
ReactiveDeps.vars.get(activeID).push(this);
}
return this._value;
}
...
}
let Stream = class {
...
set(val) {
this._value = val;
for (let entry of ReactiveDeps.vars) {
if (entry[1].indexOf(this) > -1) {
ReactiveDeps.funcs.get(entry[0])();
}
}
if (this._onChange) {
this._onChange(this._value);
}
}
...
}
let Stream = class {
constructor(val) {
this._value = val;
this._onChange = null;
}
...
subscribe(event, fn) {
if (event === 'change') {
this._onChange = fn;
}
}
}
let a = new Stream(1);
let b = new Stream(2);
let c = Merge(function(a, b) {
return a.get() + b.get();
}, [a, b]);
c.subscribe('change', function(val) {
document.querySelector('#summ').innerHTML = val;
});
setInterval(function() {
a.set(a.get() + 1);
}, 1000);