File tree 2 files changed +43
-0
lines changed
2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change
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 }
Original file line number Diff line number Diff line change
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
+ } )
You can’t perform that action at this time.
0 commit comments