mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
algorithm: percentage of letter (#1261)
This commit is contained in:
27
String/PercentageOfLetters.js
Normal file
27
String/PercentageOfLetters.js
Normal 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 }
|
16
String/test/PercentageOfLetters.test.js
Normal file
16
String/test/PercentageOfLetters.test.js
Normal 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()
|
||||||
|
})
|
||||||
|
})
|
Reference in New Issue
Block a user