JavaScript - temp - word parsing
by johnpapa
JavaScript
var str = 'this is the big cow that eats THE big moose that loves the jumping frog, that jumps over the jumping rat.';
var wordCounts = {};
var wordCounts2 = [];
var words = str.split(/\b/);
for (var i = 0; i < words.length; i++) {
//wordCounts["_" + words[i]] = (wordCounts["_" + words[i]] || 0) + 1;
if(words[i].trim().length){
wordCounts[words[i].toLowerCase()] = (wordCounts[words[i].toLowerCase()] || 0) + 1;
}
}
var Word = function(text, weight, link) {
var self = this;
self.text = text;
self.weight = weight;
self.link = link;
return self;
};
//var words = [];
var utils = {};
// Could create a utility function to do this
utils.inArray = function(searchFor, property) {
var retVal = -1;
var self = this;
for(var index=0; index < self.length; index++){
//$.each(this, function(index, item) {
var item = self[index];
if (item.hasOwnProperty(property)) {
if (item[property].toLowerCase() === searchFor.toLowerCase()) {
retVal = index;
return retVal;
}
}
};
return retVal;
};
// or we could create a function on the Array prototype indirectly
Array.prototype.inArray = utils.inArray;
for (var i = 0; i < words.length; i++) {
if(words[i].trim().length){
var j = wordCounts2.inArray(words[i], 'text');
if (j >= 0) {
wordCounts2[j].weight= (wordCounts2[j].weight || 0) + 1;
}
else {
wordCounts2.push(new Word(words[i].toLowerCase().trim(), 1));
}
}
}
console.log(words);
console.log(wordCounts);
console.log(wordCounts2);