Last active
August 29, 2015 14:02
-
-
Save batiste/d88af6303525a251c91a to your computer and use it in GitHub Desktop.
Easy expression engine in JavaScript
This file contains hidden or 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 replaceOutOfStrings(str) { | |
var index = 0, length = str.length, ch; | |
var new_str = "", inString = null, start = 0; | |
while(index < length) { | |
ch = str.charAt(index); | |
if(ch === '\\') { | |
index = index + 2; | |
continue; | |
} | |
if(ch === '"' || ch === "'") { | |
// closing a string | |
if(inString === ch) { | |
inString = null; | |
new_str = new_str + str.slice(start, index); | |
start = index; | |
} else { | |
// opening a string | |
new_str = new_str + replaceNames(str.slice(start, index)); | |
start = index; | |
inString = ch; | |
} | |
} | |
index = index + 1; | |
} | |
new_str += replaceNames(str.slice(start, index)); | |
return new_str; | |
} | |
var nameReg = /[a-zA-Z_$][0-9a-zA-Z_$]*/gm; | |
function replaceNames(str) { | |
return str.replace(nameReg, function(_name) { | |
if(!_name.match(/^_ctx./)) { | |
return '_ctx.get("'+_name+'")'; | |
} | |
return _name; | |
}); | |
} | |
function jsExpression(source) { | |
var newSource = replaceOutOfStrings(source); | |
return new Function('_ctx', 'return ' + newSource); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment