Skip to content

Instantly share code, notes, and snippets.

@delonnewman
Created January 29, 2020 00:47
Show Gist options
  • Save delonnewman/fdfa57fca0ff82c2973a09feed67b680 to your computer and use it in GitHub Desktop.
Save delonnewman/fdfa57fca0ff82c2973a09feed67b680 to your computer and use it in GitHub Desktop.
(function() {
function atom(val, options) {
var watchers = {};
var validator = options && options.validator || function () { return true; };
function transition(next) {
if (!validator(next)) {
var err = new Error(next + " failed validation");
err.name = "AssertionError";
throw err;
}
var prev = val;
val = next;
Object.keys(watchers).forEach(function (k) {
watchers[k](k, atom, prev, next);
});
}
var atom = {
addWatch: function (key, fn) {
watchers[key] = fn;
},
removeWatch: function (key) {
delete watchers[key];
},
swap: function (fn) {
var args = [val].concat([].slice.call(arguments, 1));
transition(fn.apply(null, args));
},
reset: function (v) {
transition(v);
},
deref: function () {
return val;
},
toString: function () {
return "Atom(" + JSON.stringify(val) + ")";
}
};
return atom;
}
function deref(ref) {
return ref.deref();
}
this.createAtom = atom;
this.atom = {
create: atom,
deref: deref
};
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment