SIGN IN SIGN UP

Algorithms and Data Structures implemented in JavaScript for beginners, following best practices.

34081 0 0 JavaScript
2020-10-05 17:03:56 -03:00
/**
* @function checkWordOccurrence
* @description - this function count all the words in a sentence and return an word occurrence object
* @param {string} str
* @param {boolean} isCaseSensitive
* @returns {Object}
*/
2020-10-05 17:03:56 -03:00
const checkWordOccurrence = (str, isCaseSensitive = false) => {
2020-10-06 00:08:52 -03:00
if (typeof str !== 'string') {
throw new TypeError('The first param should be a string')
}
2020-10-06 00:08:52 -03:00
if (typeof isCaseSensitive !== 'boolean') {
throw new TypeError('The second param should be a boolean')
}
2020-10-05 17:03:56 -03:00
const modifiedStr = isCaseSensitive ? str.toLowerCase() : str
2020-10-05 17:03:56 -03:00
return modifiedStr
.split(/\s+/) // remove all spaces and distribute all word in List
.reduce(
(occurrence, word) => {
occurrence[word] = occurrence[word] + 1 || 1
return occurrence
},
{}
)
2020-10-05 17:03:56 -03:00
}
2020-10-06 00:08:52 -03:00
export { checkWordOccurrence }