Skip to content

Instantly share code, notes, and snippets.

@devoncrouse
Forked from dakatsuka/dictionary.js
Created October 9, 2011 20:12
Show Gist options
  • Save devoncrouse/1274099 to your computer and use it in GitHub Desktop.
Save devoncrouse/1274099 to your computer and use it in GitHub Desktop.
Dictionary Class for Node.js
var Dictionary = function() {
this.keys = {};
this.length = 0;
this.defaultValue = null;
};
Dictionary.prototype.store = function(key, value) {
this.keys[key] = value;
this.length++;
};
Dictionary.prototype.fetch = function(key) {
var value = this.keys[key];
if (value) {
return value;
} else {
if (this.defaultValue) return this.defaultValue;
return null;
}
};
Dictionary.prototype.length = function() {
return this.keys.length();
}
Dictionary.prototype.hasKey = function(key) {
for (var k in this.keys) {
if (key == k) {
return true;
}
};
return false;
};
Dictionary.prototype.remove = function(key) {
if (this.keys[key]) {
delete this.keys[key];
this.length--;
}
};
Dictionary.prototype.reject = function(callback) {
for (var k in this.keys) {
if (callback(k, this.keys[k])) {
delete this.keys[k];
}
}
};
Dictionary.prototype.random = function() {
var keys = [];
for (var k in this.keys) {
keys.push(k);
}
return keys[Math.floor(Math.random() * keys.length)];
};
module.exports = Dictionary;
@devoncrouse
Copy link
Author

Exposed this.keys.length as length

@Daenyth
Copy link

Daenyth commented Feb 29, 2012

Pretty sure hasKey will always return false unless the first key present is the one you want

@devoncrouse
Copy link
Author

You're right - it was like that pre-fork. I changed the else {} to continue; instead of return false;

@Daenyth
Copy link

Daenyth commented Feb 29, 2012

It's redundant. You can just not have an else block at all :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment