<form id="form">Enter Phrase.
<br/>
<textarea id="phrase" rows="4" cols="50">I want what I want and I know what I want</textarea>
<br/>
<input type="button" value="Parse Phrase" id="parse" onClick=parsePhrase();>
</form>
<br/>
<div id="output"></div>
JavaScript
var hashTable = new HashTable(); // Global
function parsePhrase() {
hashTable.clear();
var phrase = document.getElementById("phrase").value;
var phraseAsStringArray = phrase.split(" ");
var len = phraseAsStringArray.length;
for (var i = 0; i < len; i++) {
hashTable.addWord(phraseAsStringArray[i], i + 1);
}
document.getElementById("output").innerHTML = hashTable.print();
}
function HashTable(obj) {
this.bins = {};
this.length = 0;
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
this.bins[p] = obj[p];
this.length++;
}
}
this.addWord = function(word, index) {
if (this.hasWord(word)) {
this.addExistingWord(word, index);
}
else {
this.addNewWord(word, index);
}
return word;
}
this.hasWord = function(word) {
return this.bins.hasOwnProperty(word);
}
this.addNewWord = function(word, index) {
this.bins[word] = index;
this.length++;
return word;
}
this.addExistingWord = function(word, index) {
var current = this.bins[word];
this.bins[word] = current + " " + index;
return word;
}
this.print = function() {
var str = "";
for (var w in this.bins) {
if (this.hasWord(w)) {
str = str + w + ": " + this.bins[w] + "<br/>";
}
}
return str;
}
this.clear = function() {
this.bins = {};
this.length = 0;
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.