commit a9251b4bac64e2da051e1c8dc5a7e3f4bae286d4
Author: James Halliday
Date: Fri Aug 27 21:12:15 2010 +0000

I've been writing a lot of node.js lately and I often need to perform complicated operations on hashes (the {} kind), so I snuck a nifty hash library into js-traverse. With this library, you can chain together hash operations like this:

var Hash = require('traverse/hash');
Hash({ a : 1, b : 2 })
    .map(function (v) { return v + 1 })
    .update({ b : 30, c : 42 })
    .filter(function (v) { return v % 2 == 0 })
    .tap(function () {
        var anyC = this.some(function (value, key) { return key == 'c' });
        // or just this.keys.some, but anyways
        console.log(anyC
            ? "There's a C key this far."
            : "There's no C key this far."
        );
    })
    .items
;

which will print "There's a C key this far." and return the hash

{ a : 2, b : 30, c : 42 }

The library borrows a lot from ruby hashes and javascript arrays. It's good for chaining together lots of operations but also good for simple stuff like Hash(obj).values since there is no Object.values() (yet).

Create a hash instance with Hash(obj). Hash instances provide:

  • map
  • forEach
  • filter
  • reduce
  • some
  • update
  • merge
  • valuesAt
  • tap
  • extract
  • items
  • keys
  • values
  • clone
  • copy

Where callbacks are provided, they usually get called with f(value, key) with the Hash instance as 'this'.

The Hash function itself also has some functions tacked on so you can do:

Hash.map({ a : 1, b : 2 }, function (x) { return x + 1 }) and get back an object without having to call .items on it: { a: 2, b: 3 }

Other libraries like prototype's Hash don't make so much of a fuss over chaining. Anyways, mine is better.

To install, just:

npm install traverse

or else:

git clone <a href="http://github.com/substack/js-traverse">http://github.com/substack/js-traverse.git</a>

then

var Hash = require('traverse/hash');
more
git clone http://substack.net/blog.git