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

Appearance settings

Commit 00a97d5

Browse filesBrowse files
authored
algorithm: percentage of letter (TheAlgorithms#1261)
1 parent 5668e64 commit 00a97d5
Copy full SHA for 00a97d5

File tree

Expand file treeCollapse file tree

2 files changed

+43
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

2 files changed

+43
-0
lines changed
Open diff view settings
Collapse file

‎String/PercentageOfLetters.js‎

Copy file name to clipboard
+27Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function percentageOfLetter
3+
* @description Return the percentage of characters in 'str'
4+
* that equal 'letter' rounded down to the nearest whole percent.
5+
* More info: https://leetcode.com/problems/percentage-of-letter-in-string/
6+
* @param {String} str
7+
* @param {String} letter
8+
* @returns {Number}
9+
* @example
10+
* const str = 'foobar', const letter = 'o'
11+
* percentageOfLetter(str, letter) // ===> 33
12+
*/
13+
const percentageOfLetter = (str, letter) => {
14+
if (typeof str !== 'string' || typeof letter !== 'string') {
15+
throw new Error('Input data must be strings')
16+
}
17+
let letterCount = 0
18+
// Iterate through the whole given text
19+
for (let i = 0; i < str.length; i++) {
20+
// Count how often the letter appears in the word
21+
letterCount += str[i].toLowerCase() === letter.toLowerCase() ? 1 : 0
22+
}
23+
const percentage = Math.floor((100 * letterCount) / str.length)
24+
return percentage
25+
}
26+
27+
export { percentageOfLetter }
Collapse file
+16Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { percentageOfLetter } from '../PercentageOfLetters'
2+
3+
describe('Percentage of Letters in a String', () => {
4+
test('Calculate percent for lower case', () => {
5+
expect(percentageOfLetter('foobar', 'o')).toEqual(33)
6+
expect(percentageOfLetter('aaabcd', 'a')).toEqual(50)
7+
})
8+
test('Calculate percent for upper case', () => {
9+
expect(percentageOfLetter('foobar', 'o')).toEqual(33)
10+
expect(percentageOfLetter('aAabcd', 'a')).toEqual(50)
11+
})
12+
test('Throwing an exception', () => {
13+
expect(() => percentageOfLetter(100, 'string')).toThrow()
14+
expect(() => percentageOfLetter('string', true)).toThrow()
15+
})
16+
})

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.