Created
November 1, 2012 10:24
-
-
Save very/3992939 to your computer and use it in GitHub Desktop.
Map definition with chaining
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 Map = (function Map(method) { | |
if (typeof method === "function") { | |
Map.prototype[method.name] = method; | |
return Map; | |
} | |
if (!(this instanceof Map)) { | |
return new Map(); | |
} | |
this.data = {}; | |
})(function has(key) { | |
return Object.prototype.hasOwnProperty.call(this.data, key); | |
})(function get(key) { | |
if (this.has(key)) { | |
return this.data[key]; | |
} | |
})(function put(key, value) { | |
var oldValue = this.get(key); | |
this.data[key] = value; | |
return oldValue; | |
})(function remove(key) { | |
var oldValue = this.get(key); | |
delete this.data[key]; | |
return oldValue; | |
})(function keys() { | |
return Object.keys(this.data).sort(); | |
})(function values() { | |
return this.keys().map(this.get.bind(this)); | |
})(function size() { | |
return this.keys().length; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment