Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trafficinc/9b396910918fd2f19fd1161102933530 to your computer and use it in GitHub Desktop.
Save trafficinc/9b396910918fd2f19fd1161102933530 to your computer and use it in GitHub Desktop.
// Dictionary - Associative Array JS
function Dictionary() {
this.datastore = new Array();
}
Dictionary.prototype.add = function(key, value) {
this.datastore[key] = value;
}
Dictionary.prototype.find = function(key) {
return this.datastore[key];
}
Dictionary.prototype.remove = function(key) {
delete this.datastore[key];
}
Dictionary.prototype.showAll = function() {
for (var key of Object.keys(this.datastore)) {
console.log(key + " -> " + this.datastore[key]);
}
}
Dictionary.prototype.count = function() {
var n = 0;
for (var key of Object.keys(this.datastore)) {
++n;
}
return n;
}
Dictionary.prototype.clear = function() {
for (var key of Object.keys(this.datastore)) {
delete this.datastore[key];
}
}
var pbook = new Dictionary();
pbook.add("Raymond","123");
pbook.add("David", "345");
pbook.add("Cynthia", "456");
console.log("Number of entries: " + pbook.count());
console.log("David's extension: " + pbook.find("David"));
pbook.showAll();
pbook.clear();
console.log("Number of entries: " + pbook.count());
//--- Result ---
/*
Number of entries: 3
David's extension: 345
Raymond -> 123
David -> 345
Cynthia -> 456
Number of entries: 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment