-
-
Save devoncrouse/1274099 to your computer and use it in GitHub Desktop.
Dictionary Class for Node.js
This file contains hidden or 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's redundant. You can just not have an else block at all :P