Created
April 12, 2017 06:08
-
-
Save vace/3377a1ce03ef16b9a42613994384f8f3 to your computer and use it in GitHub Desktop.
解析辅助类字符串:Now Time ${time}
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 renderParser(string,data){ | |
const S_CODE = 0x24 // start CODE $ | |
const S_LEFT = 0x7b // { | |
const S_RIGHT = 0x7d // } | |
const S_SPACE = 0x20 | |
let length = string.length | |
let at = 0,code,expession = '',expessionResult = '' | |
let isEnterExpression = false | |
let result = '' | |
function charAt(at){ | |
if(at < 0 || at >= length){ | |
return false | |
} | |
return string[at].charCodeAt() | |
} | |
// 解析表达式,可以考虑解析 +-*/等等 | |
function parseExpression(expession){ | |
return expession.split('.').reduce((val,key) => { | |
val = val[key] || '' | |
if(typeof val === 'function'){ | |
val = val.call(data) | |
} | |
return val | |
},data) | |
} | |
while(at < length){ | |
code = charAt(at) | |
if(code === S_CODE && charAt(at + 1) === S_LEFT){ // 下一个字符必须为{ | |
isEnterExpression = true | |
}else if(isEnterExpression && code === S_RIGHT){ // 结束 | |
expessionResult = parseExpression(expession) | |
expession = '' | |
isEnterExpression = false | |
result += expessionResult | |
}else{ | |
if(isEnterExpression){ | |
// 忽略首位和空格 | |
if(code !== S_SPACE && code !== S_LEFT){ | |
expession += string[at] | |
} | |
}else{ | |
result += string[at] | |
} | |
} | |
at++ | |
} | |
return result | |
} | |
String.prototype.render = function(data){ | |
return renderParser(this,data) | |
} | |
var greeting = 'Now Time ${time} My name is ${ name },fullName is ${fullName}, age ${age }, I am a ${job.jobName}, deep value ${ job.deep.value }'; | |
var employee = { | |
firstName:'Tom', | |
name: 'XiaoMing', | |
age: 11, | |
job: { | |
jobName: 'designer', | |
jobLevel: 'senior', | |
deep:{ | |
value:'deep_value' | |
} | |
}, | |
fullName:function(){ | |
return this.firstName + ' ' + this.name | |
}, | |
time:function(){ | |
return Date.now() | |
} | |
}; | |
var result = greeting.render(employee); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment