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 81ba695

Browse files
feat: maxChars function
1 parent 4fd0e10 commit 81ba695

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

‎src/4_maxChars/index.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// --- Task
2+
// Given a string, return the character that is most commonly used in the string.
3+
4+
// --- Examples
5+
// maxChar("abcccccccd") === "c"
6+
// maxChar("apple 1231111") === "1"
7+
8+
9+
// #1 Solution
10+
// export const maxChar = (str: string): string => {
11+
// const charsObj: Record<string, number> = {};
12+
13+
// for (let char of str) {
14+
// charsObj[char] = charsObj[char] + 1 || 1;
15+
// }
16+
17+
// const sortedEntries = Object.entries(charsObj).sort((a, b) => a[1] - b[1]);
18+
19+
// return sortedEntries[sortedEntries.length - 1][0];
20+
// }
21+
22+
23+
// max = 0;
24+
/*
25+
'hello'
26+
{
27+
h: 1,
28+
e: 1,
29+
l: 2,
30+
o: 1,
31+
}
32+
*/
33+
34+
35+
export const maxChar = (str: string): string => {
36+
const charsObj: Record<string, number> = {};
37+
let max: number = 0;
38+
let maxChar: string = '';
39+
40+
for (let char of str) {
41+
charsObj[char] = charsObj[char] + 1 || 1;
42+
}
43+
44+
for (let key in charsObj) {
45+
if (charsObj[key] > max) { // 2 > 1
46+
max = charsObj[key]; // max = 2
47+
maxChar = key; // maxChar = 'l'
48+
}
49+
}
50+
51+
return maxChar;
52+
}

‎src/4_maxChars/maxChars.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { maxChar } from '.';
2+
3+
test('maxChar function exists', () => {
4+
expect(maxChar).toBeDefined();
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 によって変換されたページ (->オリジナル) /