Here is another way:
const freqMap = s => [...s].reduce((freq,c) => {freq[c] = -~freq[c]; return freq} ,{})
Or, if you prefer the "for" loop:
function freqMap(s) { freq={}; for (let c of s) freq[c]=-~freq[c]; return freq; }
for example, freqMap ("MaMaMia") returns an object {M: 3, a: 3, i: 1}
This method uses the fact that in javascript, bitwise not at "undefined" it gives -1, while "undefined + 1" gives NaN). So, - ~ undefined is 1, - ~ 1 is 2, - ~ 2 is 3, etc.
Thus, we can iterate over the characters of a string and simply increment freq [c] without any "if". The first time we encounter the character c, freq [c] will be undefined, so we set it to - ~ freq [c], which is 1. If we subsequently meet c again, we will set freq [c] to again - ~ freq [c], which will now be 2, etc.
Simple, elegant, concise.
Yoni rabinovitch
source share