Skip to content

Commit

Permalink
updated readme and f.call(self)
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Aug 27, 2010
1 parent c7a133c commit 03f6f1e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
16 changes: 10 additions & 6 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -110,21 +110,25 @@ use.
Hash Transforms
===============

There's also a hash lib in this distribution for writing maps, filters, and
folds over hashes.
There's also a hash lib in this distribution with tons of useful functions to
operate on hashes:
map, forEach, filter, reduce, some, update, merge, tap, items, keys, values,
clone, copy

These work mostly like their array counterparts where available except they get
an extra second argument, key.

> var Hash = require('traverse/hash')
> Hash({ a : 1, b : 2 }).map(function (v) { return v + 1 }).end
> Hash({ a : 1, b : 2 }).map(function (v) { return v + 1 }).items
{ a: 2, b: 3 }

To do the same thing without chaining:

> Hash.map({ a : 1, b : 2 }, function (v) { return v + 1 })
{ a: 2, b: 3 }

Hash supports map(), filter(), and reduce(). In the first style, you can chain
together operations before the ".end". Each callback is executed like this:
f.call(hash, value, key)
The 'this' context of the function calls is the same object that the chained
functions return, so you can make nested chains.

See also [creationix's pattern/hash](http://github.com/creationix/pattern),
which does a similar thing except with hash inputs and array outputs.
8 changes: 4 additions & 4 deletions lib/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,21 @@ function Hash (hash, extra) {
map : function (f) {
var acc = { __proto__ : hash.__proto__ };
Object.keys(hash).forEach(function (key) {
acc[key] = f.call(hash, hash[key], key);
acc[key] = f.call(self, hash[key], key);
});
return Hash(acc);
},
forEach : function (f) {
Object.keys(hash).forEach(function (key) {
f.call(hash, hash[key], key);
f.call(self, hash[key], key);
});
memoized = {};
return self;
},
filter : function (f) {
var acc = { __proto__ : hash.__proto__ };
Object.keys(hash).forEach(function (key) {
if (f.call(hash, hash[key], key)) {
if (f.call(self, hash[key], key)) {
acc[key] = hash[key];
}
});
Expand All @@ -30,7 +30,7 @@ function Hash (hash, extra) {
var keys = Object.keys(hash);
if (acc === undefined) acc = keys.shift();
keys.forEach(function (key) {
acc = f.call(hash, acc, hash[key], key);
acc = f.call(self, acc, hash[key], key);
});
return acc;
},
Expand Down

0 comments on commit 03f6f1e

Please sign in to comment.