Dictionary Class (JavaScript / JS)
Mar, 03 - 2012 1 comment Uncategorized
I sorely miss the Dictionary class from AS3, but wasn’t excited by what my Googles led to and figured I’d learn more by rolling my own.
JavaScript Arrays can be used as a hash, but only with String or Numeric keys. This class lets you use any Object. A function, an Array, a class … anything. It could be faster, among other possible improvements, but this implementation has been coming in handy all over.
Dictionary = function () { this.keys = []; this.values = []; } Dictionary.prototype.get = function (key) { var index = this.keys.indexOf(key); if (index != -1) { return this.values[index]; } } Dictionary.prototype.set = function (key, value) { var index = this.keys.indexOf(key); if (index == -1) { this.keys.push(key); index = this.keys.length - 1; } this.values[index] = value; } Dictionary.prototype.remove = function (key) { var index = this.keys.indexOf(key); if (index == -1) { return undefined; } var value = this.values[index]; delete(this.values[index]); delete(this.keys[index]); return value; }
[…] Dictionary class here […]