[JS practice] Count characters in your string (计算string里字符出现的次数)

Title :
Count characters in your string (计算string里字符出现的次数)

Description :
The main idea is to count all the occuring characters(UTF-8) in string. If you have string like this aba then the result should be { ‘a’: 2, ‘b’: 1 }

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

Normal solution :

function count (string) {
  var strLength = string.length;
  var result = {};
  if(strLength != 0) { // Check the string's length whether it is equals to 0
    for (var i = 0; i < strLength; i++) { // Iterate the string
      var char = string.charAt(i);
       if (result.hasOwnProperty(char)) { // Check whether the character is already in the object
        result[char]++; // If yes, we augment the occurrence times
      } else {
        result[char] = 1; // If not, we add it to the "return" object's property
      }
    }
  }
  return result;
}

Best solution :

function count (string) {  
  var count = {};
  string.split('').forEach(function(s) {
     count[s] ? count[s]++ : count[s] = 1;
  });
  return count;
}

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s