Movatterモバイル変換


[0]ホーム

URL:


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

Commit55f502e

Browse files
algorithm: count letters (TheAlgorithms#1164)
1 parentff606a0 commit55f502e

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+
constcountLetters=(str)=>{
10+
constspecialChars=/\W/g
11+
12+
if(typeofstr!=='string'){
13+
thrownewTypeError('Input should be a string')
14+
}
15+
16+
if(specialChars.test(str)){
17+
thrownewTypeError('Input must not contain special characters')
18+
}
19+
20+
if(/\d/.test(str)){
21+
thrownewTypeError('Input must not contain numbers')
22+
}
23+
24+
constobj={}
25+
for(leti=0;i<str.toLowerCase().length;i++){
26+
constchar=str.toLowerCase().charAt(i)
27+
obj[char]=(obj[char]||0)+1
28+
}
29+
30+
returnobj
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+
constvalue='hello'
18+
constcount=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+
constvalue='HELLO'
24+
constcount=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+
constvalue='HelLo'
30+
constcount=countLetters(value)
31+
expect(count).toEqual({h:1,e:1,l:2,o:1})
32+
})
33+
})

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp