Last active
February 3, 2018 20:35
-
-
Save GreggSetzer/4ab4894246f476d1c397cb97c7e0f6db to your computer and use it in GitHub Desktop.
Javascript Interview Question: Given a string, what character appears the most?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given a string, find the character that has the highest frequency. | |
*/ | |
function maxChar(str) { | |
//Step 1: Create a data store. | |
let ds = {}; | |
//Step 2: Populate it. | |
for (let char of str) { | |
ds[char] = ds[char] + 1 || 1; | |
} | |
//Step 3: Use a comparator to find the character with highest frequency. | |
const keyArr = Object.keys(ds); | |
const comparator = (a, b) => (ds[a] > ds[b]) ? a : b; | |
return keyArr.reduce(comparator); | |
} | |
//Jest test | |
test('Finds the character most frequently used', () => { | |
expect(maxChar('x')).toEqual('x'); | |
expect(maxChar('abbccc')).toEqual('c'); | |
}); | |
//Try it | |
console.log(maxChar('abbccc')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment