Created
August 19, 2010 03:53
-
-
Save creationix/536978 to your computer and use it in GitHub Desktop.
Hash is a neat class for interable objects
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
// A Hash is an interable object | |
var Hash = module.exports = Object.create(Object.prototype, { | |
// Make for easy converting objects to hashes. | |
new: {value: function initialize(value) { | |
value.__proto__ = Hash; | |
return value; | |
}}, | |
// Implements a forEach much like the one for Array.prototype.forEach. | |
forEach: {value: function forEach(callback, thisObject) { | |
var keys = Object.keys(this), | |
length = keys.length; | |
for (var i = 0; i < length; i++) { | |
var key = keys[i]; | |
callback.call(thisObject, this[key], key, this); | |
} | |
}}, | |
// Implements a map much like the one for Array.prototype.map. | |
// Returns a normal Array instance. | |
map: {value: function map(callback, thisObject) { | |
var keys = Object.keys(this), | |
length = keys.length, | |
accum = new Array(length); | |
for (var i = 0; i < length; i++) { | |
var key = keys[i]; | |
accum[i] = callback.call(thisObject, this[key], key, this); | |
} | |
return accum; | |
}} | |
}); | |
Object.freeze(Hash); |
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 obj = Hash.new({name:"Tim", age:28}); | |
obj.forEach(function (value, key) { | |
console.log("%s %s", key, value); | |
}); | |
// name Tim | |
// age 28 | |
console.dir(obj.map(function (value, key) { | |
return key + " = " + value; | |
})); | |
// [ 'name = Tim', 'age = 28' ] | |
console.dir(obj); | |
// { name: 'Tim', age: 28 } | |
console.log(JSON.stringify(obj)); | |
// {"name":"Tim","age":28} | |
console.dir(obj instanceof Object); | |
// true | |
console.dir(Object.prototype.isPrototypeOf(obj)); | |
// true | |
console.dir(Hash.isPrototypeOf(obj)); | |
// true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment