EXERCISE · AlgoCasts
Max char
Given a string, return the character that is most commonly used in the string.
Directions
Directions
Given a string, return the character that is most commonly used in the string.
Examples#
JS
maxChar("abcccccccd") === "c"maxChar("apple 1231111") === "1"Try it first#
Copy the stub, make the 3 tests pass on your machine, then open the solution. The reveal is remembered per page in this browser.
JSexercises/maxchar/index.js
function maxChar(str) {} module.exports = maxChar;Solution#
JScompleted_exercises/maxchar/index.js
function maxChar(str) { const charMap = {}; let max = 0; let maxChar = ''; for (let char of str) { if (charMap[char]) { charMap[char]++; } else { charMap[char] = 1; } } for (let char in charMap) { if (charMap[char] > max) { max = charMap[char]; maxChar = char; } } return maxChar;} module.exports = maxChar;const maxChar = require('./index'); test('maxChar function exists', () => { expect(typeof maxChar).toEqual('function');}); test('Finds the most frequently used char', () => { expect(maxChar('a')).toEqual('a'); expect(maxChar('abcdefghijklmnaaaaa')).toEqual('a');}); test('Works with numbers in the string', () => { expect(maxChar('ab1c1d1e1f1g1')).toEqual('1');}); Verbatim from the repo at 30cf7634. Alternate tabs are the commented-out solutions with the leading // removed and nothing else changed. Run the tests locally with npx jest maxchar inside the fork.
See also