Skip to content

Instantly share code, notes, and snippets.

@nbubna
Last active December 24, 2015 02:49
Show Gist options
  • Save nbubna/6733707 to your computer and use it in GitHub Desktop.
Save nbubna/6733707 to your computer and use it in GitHub Desktop.
Safely resolve string-form variable references.
(function(scope) {
var resolve = scope.resolve = function(reference, context) {
if (resolve.RE.test(reference)) {
return resolve.unsafe(reference, context);
}
};
resolve.RE = /^([\w\$]+)?((\.[\w\$]+)|\[(\d+|'(\\'|[^'])+'|"(\\"|[^"])+")\])*$/;
resolve.unsafe = function(reference, context) {
context = context || scope;
try {
return eval('context'+(reference.charAt(0) !== '[' ? '.'+reference : reference));
} catch (e) {}
};
resolve.or = function(reference, context) {
var value = resolve(reference, context);
return value === undefined ? reference : value;
}
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment