forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercentageOfLetters.js
More file actions
Latest commit
27 lines (26 loc) · 933 Bytes
/
Copy pathPercentageOfLetters.js
File metadata and controls
27 lines (26 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @function percentageOfLetter
* @description Return the percentage of characters in 'str'
* that equal 'letter' rounded down to the nearest whole percent.
* More info: https://leetcode.com/problems/percentage-of-letter-in-string/
* @param {String} str
* @param {String} letter
* @returns {Number}
* @example
* const str = 'foobar', const letter = 'o'
* percentageOfLetter(str, letter) // ===> 33
*/
constpercentageOfLetter=(str,letter)=>{
if(typeofstr!=='string'||typeofletter!=='string'){
thrownewError('Input data must be strings')
}
letletterCount=0
// Iterate through the whole given text
for(leti=0;i<str.length;i++){
// Count how often the letter appears in the word
letterCount+=str[i].toLowerCase()===letter.toLowerCase() ? 1 : 0
}
constpercentage=Math.floor((100*letterCount)/str.length)
returnpercentage
}
export{percentageOfLetter}