From c626c99a14e175f46103cea5d19aaf2dc63ed893 Mon Sep 17 00:00:00 2001 From: Graeme Yeates Date: Fri, 11 Nov 2016 16:28:02 -0500 Subject: Handle iterators --- lib/internal/filter.js | 13 ++++++++----- mocha_test/filter.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/lib/internal/filter.js b/lib/internal/filter.js index 454cc54..e191524 100644 --- a/lib/internal/filter.js +++ b/lib/internal/filter.js @@ -1,7 +1,8 @@ -import each from 'lodash/each'; import isArrayLike from 'lodash/isArrayLike'; import noop from 'lodash/noop'; + import once from './once'; +import iterator from './iterator'; export default function _filter(eachfn, coll, iteratee, callback) { callback = once(callback || noop); @@ -14,11 +15,13 @@ export default function _filter(eachfn, coll, iteratee, callback) { }, function (err) { if (err) return callback(err); var result = []; - each(coll, function(_, index) { - if (truthValues[index] === true) { - result.push(coll[index]); + var nextElem = iterator(coll); + var elem; + while ((elem = nextElem()) !== null) { + if (truthValues[elem.key] === true) { + result.push(elem.value); } - }); + } callback(null, result); }); } diff --git a/mocha_test/filter.js b/mocha_test/filter.js index 05d9d99..8f13620 100644 --- a/mocha_test/filter.js +++ b/mocha_test/filter.js @@ -53,6 +53,37 @@ describe("filter", function () { }); }); + if (typeof Symbol === 'function' && Symbol.iterator) { + function makeIterator(array){ + var nextIndex; + let iterator = { + next: function(){ + return nextIndex < array.length ? + {value: array[nextIndex++], done: false} : + {done: true}; + } + }; + iterator[Symbol.iterator] = function() { + nextIndex = 0; // reset iterator + return iterator; + }; + return iterator; + } + + it('filter iterator', function(done){ + var a = makeIterator([500, 20, 100]); + async.filter(a, function(x, callback) { + setTimeout(function() { + callback(null, x > 20); + }, x); + }, function(err, results){ + expect(err).to.equal(null); + expect(results).to.eql([500, 100]); + done(); + }); + }); + } + it('filter error', function(done){ async.filter([3,1,2], function(x, callback){ callback('error'); -- cgit v1.2.1