2020-05-13 5kyu N00bify - Englis

2020-05-14  本文已影响0人  苦庭

https://www.codewars.com/kata/552ec968fcd1975e8100005a/javascript

讲道理,题目太长了我就不贴了,节省空间。

My answer

function n00bify(text)
{
  text = text
    .replace(/[Tt][Oo]{1,2}/g, "2")
    .replace(/fore?/g,"4")
    .replace(/[Oo]{2}/g, "00")
    .replace(/[Bb][Ee]/g, "b")
    .replace(/[Aa][Rr][Ee]/g, "r")
    .replace(/[Yy][Oo][Uu]/g, "u")
    .replace(/please/g, "plz")
    .replace(/people/g, "ppl")
    .replace(/really/g, "rly")
    .replace(/have/g, "haz")
    .replace(/know/g, "no")
    .replace(/s/g, "z")
    .replace(/S/g, "Z")
    .replace(/[\.\,\']/g, "");

  var header="";
  if(text[0] === 'W' || text[0] === 'w') header = "LOL ";
  var temp_text = header + text;
  temp_text = temp_text.replace(/[!\?]/g, "");  
  var count = temp_text.length;
  if(count >= 32) header += "OMG ";
  text = header + text;
  var wordCount = text.split(" ").length;
  text = text.split(" ").map((curVal, index) => {
    if(index%2 !== 0) return curVal.toUpperCase();
    return curVal;
  }).join(" ");
  text = text.split("").map((c) => {
    if(c === "?") {
      return Array(wordCount).fill(c).join('');
    } else if(c === "!") {
      return Array(wordCount).fill(c).map((curVal, index) => {
        if(index%2 !== 0) return "1";
        return curVal;
      }).join("");
    }
    return c;
  }).join("");
  if(text[0] === 'H' || text[0] ==='h') text = text.toUpperCase();
  return text;
}

哪里还能改进?
正则那里,可以用i模式来简化:/[Tt][Oo]{1,2}/g = /too?/gi

Best answer

function n00bify(text) {
  return [
    [/too?/gi, "2"], [/fore?/gi, "4"], [/oo/gi, "00"],
    [/be/gi, "b"], [/are/gi, "r"], [/you/gi, "u"],
    [/please/gi, "plz"], [/people/gi, "ppl"], [/really/gi, "rly"],
    [/have/gi, "haz"], [/know/gi, "no"],
    [/s/g, "z"], [/S/g, "Z"], [/[.,']/g, ""],
    [/^(?=w)/i, "LOL "], [/^(LOL |)/, function(s, lol, p, text) {
        return text.replace(/[!?]/g, "").length >= 32 ? lol + "OMG " : lol;
      }],
    [/(\S+\s+)(\S+)/g, function(s0, s1, s2) { return s1 + s2.toUpperCase(); }],
    [/^h.*/i, function(s) { return s.toUpperCase(); }],
    [/\?/g, function(s, p, text) {
        return text.split(" ").map(function() { return "?"; }).join("");
      }],
    [/!/g, function(s, p, text) {
        return text.split(" ").map(function(s, i) { return "!1"[i % 2]; }).join("");
      }],
  ].reduce(Function.prototype.apply.bind(String.prototype.replace), text);
}

好在哪?

上一篇下一篇

猜你喜欢

热点阅读