UNPKG

count-words

Version:

Count how many times words appear in the input string.

31 lines (26 loc) 794 B
"use strict"; var setOrGet = require("set-or-get"), worder = require("worder"); /** * countWords * Count how many times a word appears in the input string. * * @name countWords * @function * @param {String} input The input string. * @param {Boolean} caseInsensitive If `true`, the output will be case insensitive. * @return {Object} An object containing the keys as words and the values as * counts (how many times they appear in the input string). */ module.exports = function countWords(input, caseInsensitive) { if (caseInsensitive) { return countWords(input.toLowerCase()); } var words = worder(input), wordCount = {}; words.forEach(function (c) { setOrGet(wordCount, c, 0); wordCount[c]++; }); return wordCount; };