Back

Count characters in your string

LEVEL 6 kyu (數字越小難度越高)


Question

The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.

What if the string is empty? Then the result should be empty object literal, {}.


Summary

寫一個 function 計數字串中不同 characters 的數量,以 aba 為例,會回傳 {'a': 2, 'b': 1}。如果是空字串則回傳空物件 (參數一定是字串,且不考慮不傳參數的情況)


My Solutions

  function count (string) {
    const obj = {}
    // 將字串逐字拆成 array
    const charsArray = string.split('')

    // 如果 array 中無任何 element,表示 string 為空字串,回傳空物件
    if(!charsArray.length){
      return {}
    }

    for(let i = 0; i < charsArray.length; i++){
      // 如果該字元已作為 prop 存在於 obj 中,將該 prop 的 value + 1
      // 如果該字元不存在於 obj 中,新增該字元為 prop 並賦值為 1
      if(charsArray[i] in obj){
        obj[charsArray[i]]++
      } else {
        obj[charsArray[i]] = 1
      }
    }

    return obj
  }

  count('aba 44e  Qq;+') // { '4': 2, a: 2, b: 1, ' ': 3, e: 1, Q: 1, q: 1, ';': 1, '+': 1 }
  count('') // {}
  count() // Error
  count(123) // Error

Clever Solutions

  function count (string) {  
    const count = {}
    string.split('').forEach(s => {
      count[s] ? count[s]++ : count[s] = 1
    });
    return count
  }
  function count (string) {
    return string.split('').reduce((counts, char) => {
      counts[char] = (counts[char] || 0) + 1
      return counts;
    }, {})
  }

Furthur Discussion

若考量未傳參數、參數型別不正確的情況 (皆回傳空物件) 且不計數字串中空白:

  function count (string) {
    // 無參數 or 型別錯誤回傳空物件
    if(!string || typeof(string) !== 'string'){
      return {}
    }

    const obj = {}
    // 去除所有空白
    const charsArray = string.split('').filter(item => item !== ' ')

    if(!charsArray.length){
      return {}
    }

    for(let i = 0; i < charsArray.length; i++){
      if(charsArray[i] in obj){
        obj[charsArray[i]]++
      } else {
        obj[charsArray[i]] = 1
      }
    }

    return obj
  }

  count('aba 44e  Qq;+') // { '4': 2, a: 2, b: 1, e: 1, Q: 1, q: 1, ';': 1, '+': 1 }
  count('') // {}
  count() // {}
  count(123) // {}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus