任务描述:
Your MyRobot-specific (esoteric) scripting language called RoboScript only ever contains the following characters: F
, L
, R
, the digits 0-9
and brackets ((
and )
). Your goal is to write a function highlight
which accepts 1 required argument code
which is the RoboScript program passed in as a string and returns the script with syntax highlighting. The following commands/characters should have the following colors:
F
- Wrap this command around<span style="color: pink">
and</span>
tags so that it is highlighted pink in our editorL
- Wrap this command around<span style="color: red">
and</span>
tags so that it is highlighted red in our editorR
- Wrap this command around<span style="color: green">
and</span>
tags so that it is highlighted green in our editor- Digits from
0
through9
- Wrap these around<span style="color: orange">
and</span>
tags so that they are highlighted orange in our editor - Round Brackets - Do not apply any syntax highlighting to these characters
分析:该题较简单,直接贴答案吧。
优解:
function highlight(code) {
// Implement your syntax highlighter here
const colorMap = key => {return {
F:"pink",
L:"red",
R:"green"
}[key]||'orange'}
return code.replace(/([FLR]|\d+)\1*/g,m=>
{return `<span style="color: ${colorMap([m[0]])}">${m}</span>`}
)
}
我的:
function highlight(code) {
// Implement your syntax highlighter here
const colorMap = {
F:"pink",
L:"red",
R:"green",
'[0-9]':"orange"
}
if(/(([FLR])\2*)|([0-9]+)/g.test(code)){
return code.replace(/(([FLR])\2*)|([0-9]+)/g,function(str,char){
Object.keys(colorMap).map(key=>{
if(new RegExp(key,'g').test(str)){
str = `<span style="color: ${colorMap[key]}">${str}</span>`
}
})
return str
})
}
return code
}
二者在思路上是一样的,区别在于对于js的理解程度,理解够深就能用更少的代码量解答。