Last active
December 24, 2015 02:49
-
-
Save nbubna/6733707 to your computer and use it in GitHub Desktop.
Safely resolve string-form variable references.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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