Skip to content

Commit aee6943

Browse files
committedFeb 7, 2013
Added parallel implementation
1 parent d430ed0 commit aee6943

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
 

‎assignments/bonus-parallel.js

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* @param hash is an hash of names to functions
3+
* @param callback is the final function
4+
*/
5+
function parallel(hash, callback) {
6+
var i = 0;
7+
var count = 0;
8+
var retval = {};
9+
var cb = function(err, key, data) {
10+
if (err) {
11+
callback(err);
12+
// replace callback with noop so the final
13+
// callback will only be executed once
14+
callback = function() {};
15+
} else {
16+
i += 1;
17+
retval[key] = data;
18+
if (i === count) {
19+
callback(null, retval);
20+
}
21+
}
22+
};
23+
24+
// Count the number of functions
25+
var key;
26+
for (key in hash) {
27+
if (hash.hasOwnProperty(key)) {
28+
count += 1;
29+
}
30+
}
31+
32+
// Dispatch functions
33+
for (key in hash) {
34+
if (hash.hasOwnProperty(key)) {
35+
hash[key](function(err, data) {
36+
cb(err, key, data);
37+
});
38+
}
39+
}
40+
}
41+
42+
// example with non-erroring tasks
43+
parallel({
44+
first: function(callback) {
45+
callback(null, {
46+
piece: 'of data'
47+
});
48+
},
49+
second: function(callback) {
50+
callback(null, {
51+
piece: 'of data'
52+
});
53+
}
54+
}, function(err, data) {
55+
console.log(err, data);
56+
// > null { first: { piece: 'of data' }, second: { piece: 'of data' } }
57+
});
58+
59+
parallel({
60+
first: function(callback) {
61+
callback(null, {
62+
piece: 'of data'
63+
});
64+
},
65+
second: function(callback) {
66+
callback('well shit');
67+
}
68+
}, function(err, data) {
69+
console.log(err, data); // > well shit undefined
70+
});

0 commit comments

Comments
 (0)
Please sign in to comment.