Skip to content

Commit

Permalink
new hash lib and clone sugar
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Aug 27, 2010
1 parent 1adf75a commit 586124c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
53 changes: 53 additions & 0 deletions lib/hash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
module.exports = Hash;
var Traverse = require('traverse');

function Hash (ref) {
var hash = Traverse.clone(ref);
return {
map : function (f) {
var acc = { __proto__ : hash.__proto__ };
Object.keys(hash).forEach(function (key) {
acc[key] = f.call(hash, hash[key], key);
});
return Hash(acc);
},
forEach : function (f) {
var acc = { __proto__ : hash.__proto__ };
Object.keys(hash).forEach(function (key) {
f.call(hash, hash[key], key);
});
return Hash(hash);
},
filter : function (f) {
var acc = { __proto__ : hash.__proto__ };
Object.keys(hash).forEach(function (key) {
if (f.call(hash, hash[key], key)) {
acc[key] = hash[key];
}
});
return Hash(acc);
},
reduce : function (f, acc) {
var keys = Object.keys(hash);
if (acc === undefined) acc = keys.shift();
keys.forEach(function (key) {
acc = f.call(hash, acc, hash[key], key);
});
return acc;
},
end : hash,
};
};

Hash.map = function (ref, f) {
return Hash(ref).map(f).end;
};

Hash.filter = function (ref, f) {
return Hash(ref).filter(f).end;
};

Hash.reduce = function (ref, f, acc) {
return Hash(ref).reduce(f, acc);
};

5 changes: 5 additions & 0 deletions lib/traverse.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,8 @@ function Traverse (refObj) {
return acc;
};
}

Traverse.clone = function (obj) {
return Traverse(obj).get();
};

0 comments on commit 586124c

Please sign in to comment.