Skip to content

Instantly share code, notes, and snippets.

@ssnau
Created February 28, 2015 14:14
Show Gist options
  • Save ssnau/38c9d066b90f5c0fbebd to your computer and use it in GitHub Desktop.
Save ssnau/38c9d066b90f5c0fbebd to your computer and use it in GitHub Desktop.
riot的expression
var re_vars = /(['"\/]).*?[^\\]\1|\.\w*|\w*:|\b(?:(?:new|typeof|in|instanceof) |(?:this|true|false|null|undefined)\b|function *\()|([a-z_]\w*)/gi
// [ 1 ][ 2 ][ 3 ][ 4 ][ 5 ]
// find variable names:
// 1. skip quoted strings and regexps: "a b", 'a b', 'a \'b\'', /a b/
// 2. skip object properties: .name
// 3. skip object literals: name:
// 4. skip javascript keywords
// 5. match var name
function wrap(s, nonull) {
s = s.trim()
return !s ? 'void 0' : '(function(v){try{\n v='
// prefix vars (name => data.name)
+ (s.replace(re_vars, function(s, _, v) { return v ? 'd.'+ v : s })
// break the expression if its empty (resulting in undefined value)
|| 'x')
+ '\n}finally{\nreturn '
// default to empty string for falsy values except zero
+ (nonull ? '!v&&v!==0?"":v' : 'v')
+ '\n}}).call(d)'
}
var f = new Function('d', 'return ' + wrap('a+b'));
console.log(
f,
f({
a: 1,
b: 2
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment