Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8a6f143

Browse files
Implement a solution for finding the most used char found in a given string, wrote tests
1 parent e908411 commit 8a6f143

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

‎04_max_chars/index.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// --- Directions
2+
// Given a string, return the character that is most
3+
// commonly used in the string.
4+
// --- Examples
5+
// maxChar("abcccccccd") === "c"
6+
// maxChar("apple 1231111") === "1"
7+
8+
// Tips: Convert string to object where the keys are the character and values is the number of times the character has been found
9+
10+
function maxChar(str) {
11+
// Generate object from string
12+
const charMap = {};
13+
let max = 0;
14+
let maxChar = "";
15+
for(let char of str) {
16+
charMap[char] = charMap[char] + 1 || 1;
17+
}
18+
for (let char in charMap) {
19+
if(charMap[char] > max) {
20+
max = charMap[char];
21+
maxChar = char;
22+
}
23+
}
24+
return maxChar;
25+
}
26+
27+
module.exports = maxChar;

‎04_max_chars/test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const maxChar = require('./index');
2+
3+
test('maxChar function exists', () => {
4+
expect(typeof maxChar).toEqual('function');
5+
});
6+
7+
test('Finds the most frequently used char', () => {
8+
expect(maxChar('a')).toEqual('a');
9+
expect(maxChar('abcdefghijklmnaaaaa')).toEqual('a');
10+
});
11+
12+
test('Works with numbers in the string', () => {
13+
expect(maxChar('ab1c1d1e1f1g1')).toEqual('1');
14+
});

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /