#JavaScript - Dictionary
This allows you to store and lookup dictionary name value pairs
###Construction
var Dictionary = function Dictionary(startValues) {
this.data = startValues || {};
}
Dictionary.prototype.store = function(name, value) {
this.data[name] = value;
};
Dictionary.prototype.lookup = function(name) {
return this.data[name];
};
Dictionary.prototype.contains = function(name) {
return Object.prototype.propertyIsEnumerable.call(this.data, name);
};
Dictionary.prototype.each = function(action) {
forEachIn(this.data, action);
};
Dictionary.prototype.names = function() {
var names = [];
this.each(function(name, value) {names.push(name);});
return names;
};
Dictionary.prototype.values = function() {
var values = [];
this.each(function(name, value) {
values.push(value);
});
return values;
};
Dictionary.prototype.uniqueNames = function() {
var names = [];
this.each(function(name, value) {
if (!arrayContains(name,names))
{
names.push(name);
}
});
return names;
};
Dictionary.prototype.uniqueValues = function() {
var values = [];
this.each(function(name, value) {
if (!arrayContains(value,values))
{
values.push(value);
}
});
return values;
};
//Private Methods
function forEachIn(object, action) {
for (var property in object) {
if (object.hasOwnProperty(property))
action(property, object[property]);
}
}
function arrayContains(name, arrayData)
{
return (arrayData.indexOf(name) > -1);
}
###Example:
var colors = new Dictionary({Grover: "blue", Elmo: "red", Bert: "yellow"});
//Contains
colors.contains("Grover");
//true
//Lookup
colors.lookup("Elmo");
//'red'
//Store
colors.store("Ernie", "orange");
//Show Names
colors.names()
//[ 'Grover', 'Elmo', 'Bert', 'Earnie' ]
//View all
colors.each(function(name, color) {
console.log(name, " is ", color);
});
//Grover is blue
//Elmo is red
//Bert is yellow
//Ernie is orange
colors.values()
//['blue', 'red','yellow', 'orange']