Skip to content

Commit 00a97d5

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

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

String/PercentageOfLetters.js

Lines 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 }
Lines 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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy