Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get count of most repeated letter in a word

I am trying to get the count of the most repeated letter in a word

function GreatestCount(str)
{
    var count = {}

    for (var i = 0 ; i<str.length;i++)
    {
        var char = str[i];
        count[char] = (count[char] || 0) + 1;

    }

     //get the largest number for the letter counts
    var max = 0;

    for (var c in count) {
        if (count[c] > max) max = count[c];
    }

    return max
}

can someone explain to me why

count[char] = (count[char] || 0) + 1;// this works

count[char] += 1 // this does not work 
like image 860
Computernerd Avatar asked Dec 03 '22 16:12

Computernerd


2 Answers

Because

count[char] += 1

is equal to

count[char] = count[char] + 1

and the first time the code is run, count[char] is undefined so it's pretty much the same as

undefined + 1 // which is NaN

The working version circumvents this case by safely adding with 0 using || operator.

like image 68
Amit Joki Avatar answered Dec 05 '22 07:12

Amit Joki


Initially, count is an empty object, so it doesn't have the char property. Therefore, count[char] returns undefined.

And undefined + 1 produces NaN.

Therefore, you must inititialize it to 0 in order to make it work properly.

†: count is not really an empty object because it inherits properties from Object.prototype. It would be problematic if a char property is defined there. I recommend using count = Object.create(null) instead.

like image 23
Oriol Avatar answered Dec 05 '22 06:12

Oriol