notes on javascript, linux, and more

4.06.2009

Mirror - A Two-sided Dictionary for Javascript

I was playing around and came up with this class for "two-sided" dictionaries, meaning that there is no differentiation between keys and values.


var Mirror = function () {
this.couples = [];
};
Mirror.prototype.place = function (x, y) {
if (x == undefined) x = null;
if (y == undefined) y = null;

if (this.reflect(x) != undefined)
this.dissolve(x);
if (this.reflect(y) != undefined)
this.dissolve(y);

this.couples.push([x,y]);
};
Mirror.prototype.dissolve = function(key) {
for (var i = 0; i<this.couples.length; i++ ) {
for (var j = 0; j<2; j++ ) {
if (this.couples[i][j] === key) {
this.couples.splice(i,1);
}
}
}
};
Mirror.prototype.reflect = function (key) {
for (var i = 0; i<this.couples.length; i++ ) {
for (var j = 0; j<2; j++ ) {
if (this.couples[i][j] === key) {
return this.couples[i][j ^ 1];
}
}
}
};

var mirror = new Mirror();
// place items in the Mirror
mirror.place("johnny", "mark");
mirror.place("sammy", "sarah");
mirror.place("andrew", "engelbert");
mirror.place("yasha", "katrina");

// get the 'mate' for the key you pass in
mirror.reflect("katrina"); // yasha
mirror.reflect("engelbert"); // andrew
mirror.reflect("sammy"); // sarah

// uh oh! scandal
mirror.place("engelbert", "sarah");

// where did they go?
mirror.reflect("sammy"); // undefined, he's out of the picture.
mirror.reflect("andrew"); // undefined, he's out of the picture.

mirror.reflect("engelbert"); // sarah
mirror.reflect("sarah"); // engelbert

No comments:

About Me

My photo
chicago, il, United States
I'm a software engineer by profession.

Labels