From d9b860d666fd79498a45268c47bfd964c2fabefd Mon Sep 17 00:00:00 2001 From: Graeme Yeates Date: Sat, 1 Aug 2015 17:48:49 -0400 Subject: Implement each as iterator --- lib/async.js | 30 +++++++++++------------------- test/test-async.js | 11 ++++++----- 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/lib/async.js b/lib/async.js index 208e602..b8a2b24 100644 --- a/lib/async.js +++ b/lib/async.js @@ -77,12 +77,6 @@ ); } - function _each(coll, iterator) { - return _isArrayLike(coll) ? - _arrayEach(coll, iterator) : - _forEachOf(coll, iterator); - } - function _arrayEach(arr, iterator) { var index = -1, length = arr.length; @@ -229,24 +223,22 @@ async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); - object = object || []; - var size = _isArrayLike(object) ? object.length : _keys(object).length; - var completed = 0; - if (!size) { - return callback(null); - } - _each(object, function (value, key) { + + var nextKey = _keyIterator(object || []); + var key, running = 0; + while ((key = nextKey()) != null) { + running += 1; iterator(object[key], key, only_once(done)); - }); + } + if (!running) { + callback (null); + } function done(err) { if (err) { callback(err); } - else { - completed += 1; - if (completed >= size) { - callback(null); - } + else if (--running <= 0) { + callback(null); } } }; diff --git a/test/test-async.js b/test/test-async.js index 23aa2b9..59ff438 100755 --- a/test/test-async.js +++ b/test/test-async.js @@ -1353,8 +1353,7 @@ exports['forEachOf empty object'] = function(test){ test.ok(false, 'iterator should not be called'); callback(); }, function(err) { - if (err) throw err; - test.ok(true, 'should call callback'); + test.same(err, null, 'should call callback with err'); }); setTimeout(test.done, 25); }; @@ -1365,8 +1364,7 @@ exports['forEachOf empty array'] = function(test){ test.ok(false, 'iterator should not be called'); callback(); }, function(err) { - if (err) throw err; - test.ok(true, 'should call callback'); + test.same(err, null, 'should call callback with err'); }); setTimeout(test.done, 25); }; @@ -1765,6 +1763,7 @@ exports['map'] = { async.map(a, function(x, callback){ callback(null, x*2); }, function(err, results){ + console.log(results, [2, 4, 6]); test.same(results, [2,4,6]); test.same(a, [1,2,3]); test.done(); @@ -2034,6 +2033,7 @@ exports['filter'] = function(test){ exports['filter original untouched'] = function(test){ var a = [3,1,2]; async.filter(a, function(x, callback){ + console.log(x); callback(x % 2); }, function(results){ test.same(results, [3,1]); @@ -2071,10 +2071,11 @@ exports['reject original untouched'] = function(test){ test.expect(2); var a = [3,1,2]; async.reject(a, function(x, callback){ + console.log(x); callback(x % 2); }, function(results){ test.same(results, [2]); - test.same(a, [3,1,2]); + test.same(a, [3, 1, 2]); test.done(); }); }; -- cgit v1.2.1