Skip to content

Instantly share code, notes, and snippets.

@shamod
Created April 24, 2015 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamod/597d7215b2b54f1f3667 to your computer and use it in GitHub Desktop.
Save shamod/597d7215b2b54f1f3667 to your computer and use it in GitHub Desktop.
WordCount - Non-funcational
var para = 'How much wood would a woodchuck chuck\nIf a woodchuck could chuck wood?\nHe would chuck, he would, as much as he could,\nAnd chuck as much as a woodchuck would\nIf a woodchuck could chuck wood.';
function Words(paragraph) {
this.paragraph = paragraph;
};
Words.prototype.countWords = function() {
var mapWords = {},
arrWords = this.createArrayOfWords(this.paragraph);
arrWords.forEach(function(word) {
var count = mapWords[word];
mapWords[word] = isNaN(count) ? 1 : (count + 1);
});
return mapWords;
};
Words.prototype.createArrayOfWords = function(para) {
var arrWords = [],
arrSentences = this.parseSentence(para);
for(var i = 0; i < arrSentences.length; i++) {
var words = this.parseWord(arrSentences[i]);
words = this.cleanWord(words);
arrWords = arrWords.concat(words);
}
return arrWords;
}
Words.prototype.cleanWord = function(words) {
for(var i = 0; i < words.length; i++) {
words[i] = words[i].replace(/[.,?]$/, '').toLowerCase();
}
return words;
}
Words.prototype.parseWord = function(sentence) {
var words = sentence.split(' ');
return words;
};
Words.prototype.parseSentence = function(para) {
var sentence = para.split('\n');
return sentence;
};
var words = new Words(para);
console.log(words.countWords());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment