Skip to content

Commit

Permalink
Merge pull request #829 from megawac/find-tester
Browse files Browse the repository at this point in the history
Implement _detect via tester
  • Loading branch information
aearly committed Jul 2, 2015
2 parents 0b7a725 + 4798d8b commit 6364921
Showing 1 changed file with 16 additions and 25 deletions.
41 changes: 16 additions & 25 deletions lib/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
Expand Down Expand Up @@ -437,34 +440,16 @@
async.reject = doParallel(_reject);
async.rejectSeries = doSeries(_reject);

function _detect(eachfn, arr, iterator, main_callback) {
eachfn(arr, function (x, index, callback) {
iterator(x, function (result) {
if (result) {
main_callback(x);
main_callback = noop;
}
else {
callback();
}
});
}, function () {
main_callback();
});
}
async.detect = doParallel(_detect);
async.detectSeries = doSeries(_detect);

function _createTester(eachfn, check, defaultValue) {
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(defaultValue);
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(!defaultValue);
cb(getResult(true, x));
cb = iterator = false;
}
callback();
Expand All @@ -481,14 +466,20 @@
}

async.any =
async.some = _createTester(async.eachOf, identity, false);
async.some = _createTester(async.eachOf, toBool, identity);

async.someLimit = _createTester(async.eachOfLimit, identity, false);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);

async.all =
async.every = _createTester(async.eachOf, notId, true);
async.every = _createTester(async.eachOf, notId, notId);

async.everyLimit = _createTester(async.eachOfLimit, notId, notId);

async.everyLimit = _createTester(async.eachOfLimit, notId, true);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);

async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
Expand Down

0 comments on commit 6364921

Please sign in to comment.