Skip to content

Commit

Permalink
merge, update, and tap
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Aug 27, 2010
1 parent 92212e5 commit df5b737
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
45 changes: 39 additions & 6 deletions lib/hash.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
module.exports = Hash;
var Traverse = require('traverse');

function Hash (ref) {
var hash = Traverse.clone(ref);
function Hash (hash, extra) {
if (extra == 'clone') { // deep copy
hash = Traverse.clone(hash);
}
else if (extra == 'copy') {
var acc = { __proto__ : hash.__proto__ };
Object.keys(hash).forEach(function (key) {
acc[key] = hash[key];
});
hash = acc;
}

var self = {
map : function (f) {
var acc = { __proto__ : hash.__proto__ };
Expand All @@ -12,11 +22,10 @@ function Hash (ref) {
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);
return self;
},
filter : function (f) {
var acc = { __proto__ : hash.__proto__ };
Expand All @@ -35,6 +44,24 @@ function Hash (ref) {
});
return acc;
},
update : function (h) {
Object.keys(h).forEach(function (key) {
hash[key] = h[key];
});
return self;
},
merge : function (h) {
var acc = {};
Object.keys(hash).forEach(function (key) {
acc[key] = hash[key];
});
Object.keys(h).forEach(function (key) {
acc[key] = h[key];
});
hash = acc;
return self;
},
tap : function (f) { f.call(self, hash) },
end : hash,
items : hash
};
Expand All @@ -52,14 +79,20 @@ function Hash (ref) {
};

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

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

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

Hash.concat = function (xs) {
var hash = Hash({});
xs.forEach(function (x) { hash.update(x) });
return hash;
};

2 changes: 2 additions & 0 deletions test/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,7 @@ exports['hash traversal'] = function (assert) {

assert.equal(Hash(ref3).keys.sort().join(' '), '1337 a b c');
assert.equal(Hash(ref3).values.sort().join(' '), '2 5 7 leet');

assert.equal(Hash(ref3).length, 4);
};

0 comments on commit df5b737

Please sign in to comment.