第一步:實現語法高亮

任務描述:

Your MyRobot-specific (esoteric) scripting language called RoboScript only ever contains the following characters: FLR, 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 editor
  • L - Wrap this command around <span style="color: red"> and </span> tags so that it is highlighted red in our editor
  • R - Wrap this command around <span style="color: green"> and </span> tags so that it is highlighted green in our editor
  • Digits from 0 through 9 - 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的理解程度,理解夠深就能用更少的代碼量解答。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章