iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
0
自我挑戰組

菜鳥工程師的奇幻漂流:跟著kata活化手指和意識系列 第 10

Who likes it?

今日kata

原始題目如下:(6kyu)
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples.

翻譯:
統計按讚人數,顯示不同的文字格式。(共五種版本)

範例:
likes [] -- must be "no one likes this"
likes ["Peter"] -- must be "Peter likes this"
likes ["Jacob", "Alex"] -- must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] -- must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] -- must be "Alex, Jacob and 2 others like this"


構想&解法

function likes(names) {
  let len = names.length;
  let result = ''
  switch (len) {
    case 0:
      result = 'no one likes this'
      break;
    case 1:
      result = `${names[0]} likes this`
      break;
    case 2:
      result = `${names[0]} and ${names[1]} like this`
      break;
    case 3:
      result = `${names[0]}, ${names[1]} and ${names[2]} like this`
      break;
    default:
      result = `${names[0]}, ${names[1]} and ${names.length-2} others like this`
      break;

  }
  return result
}

土法煉鋼switch-case,計算按讚人數,將5種格式一一列出。重複很高,強迫症不要看


其他解法觀摩

function likes(names) {
  return {
    0: 'no one likes this',
    1: `${names[0]} likes this`, 
    2: `${names[0]} and ${names[1]} like this`, 
    3: `${names[0]}, ${names[1]} and ${names[2]} like this`, 
    4: `${names[0]}, ${names[1]} and ${names.length - 2} others like this`, 
  }[Math.min(4, names.length)]
}

將顯示文字形式以物件Object儲存,以objectName.propertyName取得value。


function likes (names) {
  var templates = [
    'no one likes this',
    '{name} likes this',
    '{name} and {name} like this',
    '{name}, {name} and {name} like this',
    '{name}, {name} and {n} others like this'
  ];
  var idx = Math.min(names.length, 4);
  
  return templates[idx].replace(/{name}|{n}/g, function (val) {
    return val === '{name}' ? names.shift() : names.length;
  });
}

先把所有的版本存在templates陣列中,由Math.min()決定是哪一個版本,將人名{name}或人數{n}做替換。

整理用法

字串.replace()

先前在Vowel Count這篇有整理到replace(),回顧自己常用的用法還是str.replace(substr,newSubstr)居多。

剛好這篇使用到str.replace(regexp,function)來一一替換{name}{n}:

  • /{name}|{n}/g 搜尋template中的{name} or {n}
  • function必須return要替換成的新字串
    • 如果是{name},替換成names陣列中第一個元素
    • names.shift()移除並回傳陣列第一個元素 (即names陣列本身會被異動)
    • 如果是{n},替換成names陣列目前個數

以上為今日分享的內容,若有錯誤或是建議,請再隨時和我聯繫。


上一篇
Counting Duplicates
下一篇
給自己愛的鼓勵
系列文
菜鳥工程師的奇幻漂流:跟著kata活化手指和意識30

尚未有邦友留言

立即登入留言