str.countLetters()

// ⭐️ stringCountLetters()
//    'abcc' => { a: 1, b: 1, c: 2 }
// ⭐️⭐️ reduce() 比 for loop 快兩倍❗️❗️
function stringCountLetters(str) {
  return str
    .split('')
    .reduce((dict, c) => (dict[c] = (dict[c] || 0) + 1, dict) , {});
}

// ⭐️ str.countLetters()
String.prototype.countLetters = function() {
  return stringCountLetters(this);
};

Last updated