-
-
Save devoncrouse/1274099 to your computer and use it in GitHub Desktop.
Dictionary Class for Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Pretty sure hasKey will always return false unless the first key present is the one you want
You're right - it was like that pre-fork. I changed the else {} to continue; instead of return false;
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
Exposed this.keys.length as length