Skip to content

Instantly share code, notes, and snippets.

@jneen
Last active April 5, 2016 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jneen/f6d4ddce022fa51bab745de067023ccc to your computer and use it in GitHub Desktop.
Save jneen/f6d4ddce022fa51bab745de067023ccc to your computer and use it in GitHub Desktop.
var Dynamic = function() {
var context = {}
var defaults = {}
function bind(name, val, fn) {
try {
var save = context[name];
context[name] = val;
var out = fn();
}
finally {
context[name] = save;
}
return out;
}
function get(name) {
if (typeof context[name] === 'undefined') {
return defaults[name];
}
else {
return context[name];
}
}
function setDefault(name, val) {
if (arguments.length > 1) defaults[name] = val;
return defaults[name];
}
function contextCopy() {
var out = {}
for (var k in context) {
if (!hasOwnProperty.call(context, k)) continue;
out[k] = context[k];
}
return out;
}
function remember(fn) {
var savedContext = contextCopy();
return function() {
try {
var swap = context;
context = savedContext;
var out = fn.apply(null, arguments);
}
finally {
context = swap;
}
return out;
};
}
return {
bind: bind,
get: get,
setDefault: setDefault,
remember: remember
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment