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 55f502e

Browse files
algorithm: count letters (TheAlgorithms#1164)
1 parent ff606a0 commit 55f502e

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

‎String/CountLetters.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @function countLetters
3+
* @description Given a string, count the number of each letter.
4+
* @param {String} str - The input string
5+
* @return {Object} - Object with letters and number of times
6+
* @example countLetters("hello") => {h: 1, e: 1, l: 2, o: 1}
7+
*/
8+
9+
const countLetters = (str) => {
10+
const specialChars = /\W/g
11+
12+
if (typeof str !== 'string') {
13+
throw new TypeError('Input should be a string')
14+
}
15+
16+
if (specialChars.test(str)) {
17+
throw new TypeError('Input must not contain special characters')
18+
}
19+
20+
if (/\d/.test(str)) {
21+
throw new TypeError('Input must not contain numbers')
22+
}
23+
24+
const obj = {}
25+
for (let i = 0; i < str.toLowerCase().length; i++) {
26+
const char = str.toLowerCase().charAt(i)
27+
obj[char] = (obj[char] || 0) + 1
28+
}
29+
30+
return obj
31+
}
32+
33+
export { countLetters }

‎String/test/CountLetters.test.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { countLetters } from '../CountLetters'
2+
3+
describe('CountLetters', () => {
4+
it('expect throws on use wrong param', () => {
5+
expect(() => countLetters(0)).toThrow()
6+
})
7+
8+
it('expect throws when using a number in the string', () => {
9+
expect(() => countLetters('h3llo')).toThrow()
10+
})
11+
12+
it('expect throws when using a special characters in the string', () => {
13+
expect(() => countLetters('hello!')).toThrow()
14+
})
15+
16+
it('count the letters in a string. Allows lower case', () => {
17+
const value = 'hello'
18+
const count = countLetters(value)
19+
expect(count).toEqual({ h: 1, e: 1, l: 2, o: 1 })
20+
})
21+
22+
it('count the letters in a string. Allows upper case', () => {
23+
const value = 'HELLO'
24+
const count = countLetters(value)
25+
expect(count).toEqual({ h: 1, e: 1, l: 2, o: 1 })
26+
})
27+
28+
it('count the letters in a string. Allows upper and lower case', () => {
29+
const value = 'HelLo'
30+
const count = countLetters(value)
31+
expect(count).toEqual({ h: 1, e: 1, l: 2, o: 1 })
32+
})
33+
})

0 commit comments

Comments
(0)

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