Instantly share code, notes, and snippets.

@vace vace/renderString.js
Created Apr 12, 2017

Embed
What would you like to do?
解析辅助类字符串:Now Time ${time}
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