Skip to content

Commit

Permalink
Add async.transform
Browse files Browse the repository at this point in the history
  • Loading branch information
megawac committed Aug 24, 2015
1 parent b2fded3 commit 6fbc797
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/async.js
Expand Up @@ -379,7 +379,7 @@
callback(err);
});
}, function (err) {
callback(err || null, memo);
callback(err, memo);
});
};

Expand All @@ -389,6 +389,20 @@
async.reduce(reversed, memo, iterator, callback);
};

async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}

async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};

function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
Expand Down
53 changes: 53 additions & 0 deletions test/test-async.js
Expand Up @@ -2023,6 +2023,59 @@ exports['foldr alias'] = function(test){
test.done();
};

exports['transform implictly determines memo if not provided'] = function(test){
async.transform([1,2,3], function(memo, x, v, callback){
memo.push(x + 1);
callback();
}, function(err, result){
test.same(result, [2, 3, 4]);
test.done();
});
};

exports['transform async with object memo'] = function(test){
test.expect(2);

async.transform([1,3,2], {}, function(memo, v, k, callback){
setTimeout(function() {
memo[k] = v;
callback();
});
}, function(err, result) {
test.equals(err, null);
test.same(result, {
0: 1,
1: 3,
2: 2
});
test.done();
});
};

exports['transform iterating object'] = function(test){
test.expect(2);

async.transform({a: 1, b: 3, c: 2}, function(memo, v, k, callback){
setTimeout(function() {
memo[k] = v + 1;
callback();
});
}, function(err, result) {
test.equals(err, null);
test.same(result, {a: 2, b: 4, c: 3});
test.done();
});
};

exports['transform error'] = function(test){
async.transform([1,2,3], function(a, v, k, callback){
callback('error');
}, function(err){
test.equals(err, 'error');
test.done();
});
};

exports['filter'] = function(test){
async.filter([3,1,2], filterIterator, function(results){
test.same(results, [3,1]);
Expand Down

0 comments on commit 6fbc797

Please sign in to comment.