Hello everyone! This is the fifth post in my new node.js modules you should know about article series.
The first post was about dnode - the freestyle rpc library for node, the second was about optimist - the lightweight options parser for node, the third was about lazy - lazy lists for node, the fourth was about request - the swiss army knife of HTTP streaming.
This time I'll introduce you to hashish. Hashish is written by James Halliday, who's my co-founder of Browserling and Testling. In case you're wondering why I am blogging about so many of his modules, it's because he's written 88 of them and each one of them is absolutely brilliant.
Hashish is a JavaScript hash combinator library, or in other words, it contains a bunch of hash data structure manipulation functions.
Check out this example,
var Hash = require('hashish');
Hash({ a : 1, b : 2, c : 3, d : 4 })
.map(function (x) { return x * 10 })
.filter(function (x) { return x < 30 })
.forEach(function (x, key) {
console.log(key + ' => ' + x);
})
;
Here a Hash
object is constructed from the hash { a : 1, b : 2, c : 3, d : 4 }
. Next, a function that multiplies each hash value by 10 is map
ped over. At this moment the hash has become { a : 10, b : 20, c : 30, d : 40 }
Then a filter
is applied that filters only hash elements that have value less than 30
. At this point hash is { a : 10, b : 20 }
. Finally forEach
combinator is applied all the elements that are left and the key, value pair is printed, producing the following output:
a => 10 b => 20
Notice how similar the interface for hash manipulation is to the node-lazy that I wrote about a few days ago. All the combinators can be chained so your code stays beautiful.
If you can't or don't want to chain the functions, hashish also allows each function in the chainable interface to be attached to Hash in chainless form:
var Hash = require('hashish');
var obj = { a : 1, b : 2, c : 3, d : 4 };
var mapped = Hash.map(obj, function (x) {
return x * 10
});
console.dir(mapped);
Notice how this code calls Hash.map
on obj
hash. The output is each hash value multiplied by 10:
{ a: 10, b: 20, c: 30, d: 40 }
Hashish also provides various attributes in the chaining interface and functions in the Hash.xxx interface. For example:
$ node > var Hash = require('hashish'); > var obj = { a : 1, b : 2, c : 3, d : 4 }; > > Hash(obj).keys [ 'a', 'b', 'c', 'd' ] > Hash(obj).values [ 1, 2, 3, 4 ] > Hash(obj).length 4
You can install hashish through npm:
npm install hashish