Skip to content

Commit

Permalink
Merge pull request #892 from caolan/transform
Browse files Browse the repository at this point in the history
Add async.transform
  • Loading branch information
aearly committed Oct 25, 2015
2 parents f88e57c + 6fbc797 commit ea357ef
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
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@
callback(err);
});
}, function (err) {
callback(err || null, memo);
callback(err, memo);
});
};

Expand All @@ -390,6 +390,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
Original file line number Diff line number Diff line change
Expand Up @@ -2041,6 +2041,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 ea357ef

Please sign in to comment.