algorithm: percentage of letter (#1261)

This commit is contained in:
Alex Popov
2022-11-01 06:45:02 +03:00
committed by GitHub
parent 5668e64b29
commit 00a97d5e1b
2 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,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
*/
const percentageOfLetter = (str, letter) => {
if (typeof str !== 'string' || typeof letter !== 'string') {
throw new Error('Input data must be strings')
}
let letterCount = 0
// Iterate through the whole given text
for (let i = 0; i < str.length; i++) {
// Count how often the letter appears in the word
letterCount += str[i].toLowerCase() === letter.toLowerCase() ? 1 : 0
}
const percentage = Math.floor((100 * letterCount) / str.length)
return percentage
}
export { percentageOfLetter }

View File

@ -0,0 +1,16 @@
import { percentageOfLetter } from '../PercentageOfLetters'
describe('Percentage of Letters in a String', () => {
test('Calculate percent for lower case', () => {
expect(percentageOfLetter('foobar', 'o')).toEqual(33)
expect(percentageOfLetter('aaabcd', 'a')).toEqual(50)
})
test('Calculate percent for upper case', () => {
expect(percentageOfLetter('foobar', 'o')).toEqual(33)
expect(percentageOfLetter('aAabcd', 'a')).toEqual(50)
})
test('Throwing an exception', () => {
expect(() => percentageOfLetter(100, 'string')).toThrow()
expect(() => percentageOfLetter('string', true)).toThrow()
})
})