Skip to content

Instantly share code, notes, and snippets.

@creationix
Created August 19, 2010 03:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creationix/536978 to your computer and use it in GitHub Desktop.
Save creationix/536978 to your computer and use it in GitHub Desktop.
Hash is a neat class for interable objects
// 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);
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