RobotScript#1第一步:实现语法高亮

任务描述:

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的理解程度,理解够深就能用更少的代码量解答。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Beq

我们应该鼓励分享,开源精神

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值