summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlexander Early <alexander.early@gmail.com>2016-02-09 19:30:28 -0800
committerAlexander Early <alexander.early@gmail.com>2016-02-09 19:30:28 -0800
commit34f666a735d68eb563d1ff5d22fc85d176dcdcc2 (patch)
treeefeab36210b24c58c5faae1817fb32d5e84ccbb5
parentf4f2742270bc4c7f1325620bddc804379a8c0486 (diff)
downloadasync-34f666a735d68eb563d1ff5d22fc85d176dcdcc2.tar.gz
move package manager files during build process, update main paths
-rw-r--r--Makefile15
-rw-r--r--bower.json27
-rw-r--r--build/CHANGELOG.md117
-rw-r--r--build/LICENSE19
-rw-r--r--build/README.md1795
-rw-r--r--build/async.js1838
-rw-r--r--build/async.min.js2
-rw-r--r--build/bower.json68
-rw-r--r--build/component.json17
-rw-r--r--build/es/apply.js9
-rw-r--r--build/es/applyEach.js6
-rw-r--r--build/es/applyEachSeries.js6
-rw-r--r--build/es/asyncify.js26
-rw-r--r--build/es/auto.js109
-rw-r--r--build/es/cargo.js7
-rw-r--r--build/es/compose.js9
-rw-r--r--build/es/concat.js6
-rw-r--r--build/es/concatSeries.js6
-rw-r--r--build/es/constant.js10
-rw-r--r--build/es/detect.js9
-rw-r--r--build/es/detectLimit.js9
-rw-r--r--build/es/detectSeries.js9
-rw-r--r--build/es/dir.js5
-rw-r--r--build/es/doDuring.js12
-rw-r--r--build/es/doUntil.js9
-rw-r--r--build/es/doWhilst.js10
-rw-r--r--build/es/during.js25
-rw-r--r--build/es/each.js8
-rw-r--r--build/es/eachLimit.js9
-rw-r--r--build/es/eachOf.js34
-rw-r--r--build/es/eachOfLimit.js7
-rw-r--r--build/es/eachOfSeries.js40
-rw-r--r--build/es/eachSeries.js8
-rw-r--r--build/es/ensureAsync.js24
-rw-r--r--build/es/every.js7
-rw-r--r--build/es/everyLimit.js7
-rw-r--r--build/es/filter.js6
-rw-r--r--build/es/filterLimit.js6
-rw-r--r--build/es/filterSeries.js6
-rw-r--r--build/es/forever.js17
-rw-r--r--build/es/index.js228
-rw-r--r--build/es/internal/applyEach.js22
-rw-r--r--build/es/internal/concat.js13
-rw-r--r--build/es/internal/consoleFunc.js23
-rw-r--r--build/es/internal/createTester.js26
-rw-r--r--build/es/internal/doParallel.js9
-rw-r--r--build/es/internal/doParallelLimit.js9
-rw-r--r--build/es/internal/doSeries.js9
-rw-r--r--build/es/internal/eachOfLimit.js49
-rw-r--r--build/es/internal/filter.js20
-rw-r--r--build/es/internal/findGetResult.js5
-rw-r--r--build/es/internal/keyIterator.js23
-rw-r--r--build/es/internal/map.js19
-rw-r--r--build/es/internal/notId.js5
-rw-r--r--build/es/internal/onlyOnce.js9
-rw-r--r--build/es/internal/parallel.js22
-rw-r--r--build/es/internal/queue.js140
-rw-r--r--build/es/internal/reject.js11
-rw-r--r--build/es/internal/setImmediate.js19
-rw-r--r--build/es/internal/withoutIndex.js7
-rw-r--r--build/es/iterator.js17
-rw-r--r--build/es/log.js5
-rw-r--r--build/es/map.js6
-rw-r--r--build/es/mapLimit.js6
-rw-r--r--build/es/mapSeries.js6
-rw-r--r--build/es/memoize.js36
-rw-r--r--build/es/nextTick.js7
-rw-r--r--build/es/parallel.js8
-rw-r--r--build/es/parallelLimit.js8
-rw-r--r--build/es/priorityQueue.js72
-rw-r--r--build/es/queue.js9
-rw-r--r--build/es/reduce.js14
-rw-r--r--build/es/reduceRight.js10
-rw-r--r--build/es/reject.js6
-rw-r--r--build/es/rejectLimit.js6
-rw-r--r--build/es/rejectSeries.js6
-rw-r--r--build/es/retry.js77
-rw-r--r--build/es/seq.js28
-rw-r--r--build/es/series.js8
-rw-r--r--build/es/setImmediate.js5
-rw-r--r--build/es/some.js8
-rw-r--r--build/es/someLimit.js7
-rw-r--r--build/es/sortBy.js23
-rw-r--r--build/es/times.js8
-rw-r--r--build/es/timesLimit.js8
-rw-r--r--build/es/timesSeries.js8
-rw-r--r--build/es/transform.js19
-rw-r--r--build/es/unmemoize.js7
-rw-r--r--build/es/until.js9
-rw-r--r--build/es/waterfall.js32
-rw-r--r--build/es/whilst.js15
-rw-r--r--build/package.json97
-rw-r--r--component.json12
-rw-r--r--index.js1
-rw-r--r--package.json30
95 files changed, 4698 insertions, 953 deletions
diff --git a/Makefile b/Makefile
index 541cb34..ca9fe84 100644
--- a/Makefile
+++ b/Makefile
@@ -75,9 +75,20 @@ $(BUILDDIR)/es/%.js: lib/%.js
test-build:
mocha support/build.test.js
-.PHONY: build-modules build-bundle build-dist build-es test-build
+build-config: $(BUILDDIR)/package.json $(BUILDDIR)/component.json $(BUILDDIR)/bower.json $(BUILDDIR)/README.md $(BUILDDIR)/LICENSE $(BUILDDIR)/CHANGELOG.md
-build: clean build-bundle build-dist build-es test-build
+bower.json: package.json
+ support/sync-package-managers.js
+
+component.json: package.json
+ support/sync-package-managers.js
+
+$(BUILDDIR)/%: %
+ cp $< $@
+
+.PHONY: build-modules build-bundle build-dist build-es build-config test-build
+
+build: clean build-bundle build-dist build-es build-config test-build
.PHONY: test lint build all clean
diff --git a/bower.json b/bower.json
index e89f078..b2a4f3c 100644
--- a/bower.json
+++ b/bower.json
@@ -1,12 +1,12 @@
{
"name": "async",
"description": "Higher-order functions and common patterns for asynchronous code",
- "main": "lib/async.js",
+ "main": "index.js",
"keywords": [
"async",
"callback",
- "utility",
- "module"
+ "module",
+ "utility"
],
"license": "MIT",
"repository": {
@@ -14,11 +14,19 @@
"url": "https://github.com/caolan/async.git"
},
"devDependencies": {
+ "babel-cli": "^6.3.17",
+ "babel-core": "^6.3.26",
+ "babel-plugin-add-module-exports": "~0.1.2",
+ "babel-plugin-transform-es2015-modules-commonjs": "^6.3.16",
+ "babel-preset-es2015": "^6.3.13",
+ "babelify": "^7.2.0",
"benchmark": "bestiejs/benchmark.js",
"bluebird": "^2.9.32",
"chai": "^3.1.0",
"coveralls": "^2.11.2",
"es6-promise": "^2.3.0",
+ "fs-extra": "^0.26.3",
+ "gulp": "~3.9.0",
"jscs": "^1.13.1",
"jshint": "~2.8.0",
"karma": "^0.13.2",
@@ -26,15 +34,19 @@
"karma-firefox-launcher": "^0.1.6",
"karma-mocha": "^0.2.0",
"karma-mocha-reporter": "^1.0.2",
- "lodash": "^3.9.0",
- "mkdirp": "~0.5.1",
"mocha": "^2.2.5",
"native-promise-only": "^0.8.0-a",
"nodeunit": ">0.0.0",
"nyc": "^2.1.0",
+ "recursive-readdir": "^1.3.0",
+ "rimraf": "^2.5.0",
+ "rollup": "^0.25.0",
+ "rollup-plugin-npm": "~1.3.0",
"rsvp": "^3.0.18",
"semver": "^4.3.6",
"uglify-js": "~2.4.0",
+ "vinyl-buffer": "~1.0.0",
+ "vinyl-source-stream": "~1.1.0",
"xyz": "^0.5.0",
"yargs": "~3.9.1"
},
@@ -52,6 +64,5 @@
],
"authors": [
"Caolan McMahon"
- ],
- "version": "1.5.0"
-}
+ ]
+} \ No newline at end of file
diff --git a/build/CHANGELOG.md b/build/CHANGELOG.md
new file mode 100644
index 0000000..0f28c92
--- /dev/null
+++ b/build/CHANGELOG.md
@@ -0,0 +1,117 @@
+# v1.5.1
+- Fix issue with `pause` in `queue` with concurrency enabled (#946)
+- `while` and `until` now pass the final result to callback (#963)
+
+# v1.5.0
+
+- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) (#892)
+- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. (#873)
+- `auto` now accepts an optional `concurrency` argument to limit the number of running tasks (#637)
+- Added `queue#workersList()`, to retrieve the list of currently running tasks. (#891)
+- Various code simplifications (#896, #904)
+- Various doc fixes :scroll: (#890, #894, #903, #905, #912)
+
+# v1.4.2
+
+- Ensure coverage files don't get published on npm (#879)
+
+# v1.4.1
+
+- Add in overlooked `detectLimit` method (#866)
+- Removed unnecessary files from npm releases (#861)
+- Removed usage of a reserved word to prevent :boom: in older environments (#870)
+
+# v1.4.0
+
+- `asyncify` now supports promises (#840)
+- Added `Limit` versions of `filter` and `reject` (#836)
+- Add `Limit` versions of `detect`, `some` and `every` (#828, #829)
+- `some`, `every` and `detect` now short circuit early (#828, #829)
+- Improve detection of the global object (#804), enabling use in WebWorkers
+- `whilst` now called with arguments from iterator (#823)
+- `during` now gets called with arguments from iterator (#824)
+- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0))
+
+
+# v1.3.0
+
+New Features:
+- Added `constant`
+- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. (#671, #806)
+- Added `during` and `doDuring`, which are like `whilst` with an async truth test. (#800)
+- `retry` now accepts an `interval` parameter to specify a delay between retries. (#793)
+- `async` should work better in Web Workers due to better `root` detection (#804)
+- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` (#642)
+- Various internal updates (#786, #801, #802, #803)
+- Various doc fixes (#790, #794)
+
+Bug Fixes:
+- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. (#740, #744, #783)
+
+
+# v1.2.1
+
+Bug Fix:
+
+- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. (#782)
+
+
+# v1.2.0
+
+New Features:
+
+- Added `timesLimit` (#743)
+- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. (#747, #772)
+
+Bug Fixes:
+
+- Fixed a regression in `each` and family with empty arrays that have additional properties. (#775, #777)
+
+
+# v1.1.1
+
+Bug Fix:
+
+- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. (#782)
+
+
+# v1.1.0
+
+New Features:
+
+- `cargo` now supports all of the same methods and event callbacks as `queue`.
+- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. (#769)
+- Optimized `map`, `eachOf`, and `waterfall` families of functions
+- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array (#667).
+- The callback is now optional for the composed results of `compose` and `seq`. (#618)
+- Reduced file size by 4kb, (minified version by 1kb)
+- Added code coverage through `nyc` and `coveralls` (#768)
+
+Bug Fixes:
+
+- `forever` will no longer stack overflow with a synchronous iterator (#622)
+- `eachLimit` and other limit functions will stop iterating once an error occurs (#754)
+- Always pass `null` in callbacks when there is no error (#439)
+- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue (#668)
+- `each` and family will properly handle an empty array (#578)
+- `eachSeries` and family will finish if the underlying array is modified during execution (#557)
+- `queue` will throw if a non-function is passed to `q.push()` (#593)
+- Doc fixes (#629, #766)
+
+
+# v1.0.0
+
+No known breaking changes, we are simply complying with semver from here on out.
+
+Changes:
+
+- Start using a changelog!
+- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) (#168 #704 #321)
+- Detect deadlocks in `auto` (#663)
+- Better support for require.js (#527)
+- Throw if queue created with concurrency `0` (#714)
+- Fix unneeded iteration in `queue.resume()` (#758)
+- Guard against timer mocking overriding `setImmediate` (#609 #611)
+- Miscellaneous doc fixes (#542 #596 #615 #628 #631 #690 #729)
+- Use single noop function internally (#546)
+- Optimize internal `_each`, `_map` and `_keys` functions.
diff --git a/build/LICENSE b/build/LICENSE
new file mode 100644
index 0000000..8f29698
--- /dev/null
+++ b/build/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2010-2014 Caolan McMahon
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/build/README.md b/build/README.md
new file mode 100644
index 0000000..0ec79c1
--- /dev/null
+++ b/build/README.md
@@ -0,0 +1,1795 @@
+# Async.js
+
+[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async)
+[![NPM version](http://img.shields.io/npm/v/async.svg)](https://www.npmjs.org/package/async)
+[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master)
+[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+
+
+Async is a utility module which provides straight-forward, powerful functions
+for working with asynchronous JavaScript. Although originally designed for
+use with [Node.js](http://nodejs.org) and installable via `npm install async`,
+it can also be used directly in the browser.
+
+Async is also installable via:
+
+- [bower](http://bower.io/): `bower install async`
+- [component](https://github.com/component/component): `component install
+ caolan/async`
+- [jam](http://jamjs.org/): `jam install async`
+- [spm](http://spmjs.io/): `spm install async`
+
+Async provides around 20 functions that include the usual 'functional'
+suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns
+for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these
+functions assume you follow the Node.js convention of providing a single
+callback as the last argument of your `async` function.
+
+
+## Quick Examples
+
+```javascript
+async.map(['file1','file2','file3'], fs.stat, function(err, results){
+ // results is now an array of stats for each file
+});
+
+async.filter(['file1','file2','file3'], fs.exists, function(results){
+ // results now equals an array of the existing files
+});
+
+async.parallel([
+ function(){ ... },
+ function(){ ... }
+], callback);
+
+async.series([
+ function(){ ... },
+ function(){ ... }
+]);
+```
+
+There are many more functions available so take a look at the docs below for a
+full list. This module aims to be comprehensive, so if you feel anything is
+missing please create a GitHub issue for it.
+
+## Common Pitfalls <sub>[(StackOverflow)](http://stackoverflow.com/questions/tagged/async.js)</sub>
+### Synchronous iteration functions
+
+If you get an error like `RangeError: Maximum call stack size exceeded.` or other stack overflow issues when using async, you are likely using a synchronous iterator. By *synchronous* we mean a function that calls its callback on the same tick in the javascript event loop, without doing any I/O or using any timers. Calling many callbacks iteratively will quickly overflow the stack. If you run into this issue, just defer your callback with `async.setImmediate` to start a new call stack on the next tick of the event loop.
+
+This can also arise by accident if you callback early in certain cases:
+
+```js
+async.eachSeries(hugeArray, function iterator(item, callback) {
+ if (inCache(item)) {
+ callback(null, cache[item]); // if many items are cached, you'll overflow
+ } else {
+ doSomeIO(item, callback);
+ }
+}, function done() {
+ //...
+});
+```
+
+Just change it to:
+
+```js
+async.eachSeries(hugeArray, function iterator(item, callback) {
+ if (inCache(item)) {
+ async.setImmediate(function () {
+ callback(null, cache[item]);
+ });
+ } else {
+ doSomeIO(item, callback);
+ //...
+```
+
+Async guards against synchronous functions in some, but not all, cases. If you are still running into stack overflows, you can defer as suggested above, or wrap functions with [`async.ensureAsync`](#ensureAsync) Functions that are asynchronous by their nature do not have this problem and don't need the extra callback deferral.
+
+If JavaScript's event loop is still a bit nebulous, check out [this article](http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/) or [this talk](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html) for more detailed information about how it works.
+
+
+### Multiple callbacks
+
+Make sure to always `return` when calling a callback early, otherwise you will cause multiple callbacks and unpredictable behavior in many cases.
+
+```js
+async.waterfall([
+ function (callback) {
+ getSomething(options, function (err, result) {
+ if (err) {
+ callback(new Error("failed getting something:" + err.message));
+ // we should return here
+ }
+ // since we did not return, this callback still will be called and
+ // `processData` will be called twice
+ callback(null, result);
+ });
+ },
+ processData
+], done)
+```
+
+It is always good practice to `return callback(err, result)` whenever a callback call is not the last statement of a function.
+
+
+### Binding a context to an iterator
+
+This section is really about `bind`, not about `async`. If you are wondering how to
+make `async` execute your iterators in a given context, or are confused as to why
+a method of another library isn't working as an iterator, study this example:
+
+```js
+// Here is a simple object with an (unnecessarily roundabout) squaring method
+var AsyncSquaringLibrary = {
+ squareExponent: 2,
+ square: function(number, callback){
+ var result = Math.pow(number, this.squareExponent);
+ setTimeout(function(){
+ callback(null, result);
+ }, 200);
+ }
+};
+
+async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){
+ // result is [NaN, NaN, NaN]
+ // This fails because the `this.squareExponent` expression in the square
+ // function is not evaluated in the context of AsyncSquaringLibrary, and is
+ // therefore undefined.
+});
+
+async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){
+ // result is [1, 4, 9]
+ // With the help of bind we can attach a context to the iterator before
+ // passing it to async. Now the square function will be executed in its
+ // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`
+ // will be as expected.
+});
+```
+
+## Download
+
+The source is available for download from
+[GitHub](https://github.com/caolan/async/blob/master/lib/async.js).
+Alternatively, you can install using Node Package Manager (`npm`):
+
+ npm install async
+
+As well as using Bower:
+
+ bower install async
+
+__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed
+
+## In the Browser
+
+So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5.
+
+Usage:
+
+```html
+<script type="text/javascript" src="async.js"></script>
+<script type="text/javascript">
+
+ async.map(data, asyncProcess, function(err, results){
+ alert(results);
+ });
+
+</script>
+```
+
+## Documentation
+
+Some functions are also available in the following forms:
+* `<name>Series` - the same as `<name>` but runs only a single async operation at a time
+* `<name>Limit` - the same as `<name>` but runs a maximum of `limit` async operations at a time
+
+### Collections
+
+* [`each`](#each), `eachSeries`, `eachLimit`
+* [`forEachOf`](#forEachOf), `forEachOfSeries`, `forEachOfLimit`
+* [`map`](#map), `mapSeries`, `mapLimit`
+* [`filter`](#filter), `filterSeries`, `filterLimit`
+* [`reject`](#reject), `rejectSeries`, `rejectLimit`
+* [`reduce`](#reduce), [`reduceRight`](#reduceRight)
+* [`detect`](#detect), `detectSeries`, `detectLimit`
+* [`sortBy`](#sortBy)
+* [`some`](#some), `someLimit`
+* [`every`](#every), `everyLimit`
+* [`concat`](#concat), `concatSeries`
+
+### Control Flow
+
+* [`series`](#seriestasks-callback)
+* [`parallel`](#parallel), `parallelLimit`
+* [`whilst`](#whilst), [`doWhilst`](#doWhilst)
+* [`until`](#until), [`doUntil`](#doUntil)
+* [`during`](#during), [`doDuring`](#doDuring)
+* [`forever`](#forever)
+* [`waterfall`](#waterfall)
+* [`compose`](#compose)
+* [`seq`](#seq)
+* [`applyEach`](#applyEach), `applyEachSeries`
+* [`queue`](#queue), [`priorityQueue`](#priorityQueue)
+* [`cargo`](#cargo)
+* [`auto`](#auto)
+* [`retry`](#retry)
+* [`iterator`](#iterator)
+* [`times`](#times), `timesSeries`, `timesLimit`
+
+### Utils
+
+* [`apply`](#apply)
+* [`nextTick`](#nextTick)
+* [`memoize`](#memoize)
+* [`unmemoize`](#unmemoize)
+* [`ensureAsync`](#ensureAsync)
+* [`constant`](#constant)
+* [`asyncify`](#asyncify)
+* [`wrapSync`](#wrapSync)
+* [`log`](#log)
+* [`dir`](#dir)
+* [`noConflict`](#noConflict)
+
+## Collections
+
+<a name="forEach" />
+<a name="each" />
+### each(arr, iterator, [callback])
+
+Applies the function `iterator` to each item in `arr`, in parallel.
+The `iterator` is called with an item from the list, and a callback for when it
+has finished. If the `iterator` passes an error to its `callback`, the main
+`callback` (for the `each` function) is immediately called with the error.
+
+Note, that since this function applies `iterator` to each item in parallel,
+there is no guarantee that the iterator functions will complete in order.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err)` which must be called once it has
+ completed. If no error has occurred, the `callback` should be run without
+ arguments or with an explicit `null` argument. The array index is not passed
+ to the iterator. If you need the index, use [`forEachOf`](#forEachOf).
+* `callback(err)` - *Optional* A callback which is called when all `iterator` functions
+ have finished, or an error occurs.
+
+__Examples__
+
+
+```js
+// assuming openFiles is an array of file names and saveFile is a function
+// to save the modified contents of that file:
+
+async.each(openFiles, saveFile, function(err){
+ // if any of the saves produced an error, err would equal that error
+});
+```
+
+```js
+// assuming openFiles is an array of file names
+
+async.each(openFiles, function(file, callback) {
+
+ // Perform operation on file here.
+ console.log('Processing file ' + file);
+
+ if( file.length > 32 ) {
+ console.log('This file name is too long');
+ callback('File name too long');
+ } else {
+ // Do work to process file here
+ console.log('File processed');
+ callback();
+ }
+}, function(err){
+ // if any of the file processing produced an error, err would equal that error
+ if( err ) {
+ // One of the iterations produced an error.
+ // All processing will now stop.
+ console.log('A file failed to process');
+ } else {
+ console.log('All files have been processed successfully');
+ }
+});
+```
+
+__Related__
+
+* eachSeries(arr, iterator, [callback])
+* eachLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+<a name="forEachOf" />
+<a name="eachOf" />
+
+### forEachOf(obj, iterator, [callback])
+
+Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator.
+
+__Arguments__
+
+* `obj` - An object or array to iterate over.
+* `iterator(item, key, callback)` - A function to apply to each item in `obj`.
+The `key` is the item's key, or index in the case of an array. The iterator is
+passed a `callback(err)` which must be called once it has completed. If no
+error has occurred, the callback should be run without arguments or with an
+explicit `null` argument.
+* `callback(err)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs.
+
+__Example__
+
+```js
+var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
+var configs = {};
+
+async.forEachOf(obj, function (value, key, callback) {
+ fs.readFile(__dirname + value, "utf8", function (err, data) {
+ if (err) return callback(err);
+ try {
+ configs[key] = JSON.parse(data);
+ } catch (e) {
+ return callback(e);
+ }
+ callback();
+ })
+}, function (err) {
+ if (err) console.error(err.message);
+ // configs is now a map of JSON data
+ doSomethingWith(configs);
+})
+```
+
+__Related__
+
+* forEachOfSeries(obj, iterator, [callback])
+* forEachOfLimit(obj, limit, iterator, [callback])
+
+---------------------------------------
+
+<a name="map" />
+### map(arr, iterator, [callback])
+
+Produces a new array of values by mapping each value in `arr` through
+the `iterator` function. The `iterator` is called with an item from `arr` and a
+callback for when it has finished processing. Each of these callback takes 2 arguments:
+an `error`, and the transformed item from `arr`. If `iterator` passes an error to its
+callback, the main `callback` (for the `map` function) is immediately called with the error.
+
+Note, that since this function applies the `iterator` to each item in parallel,
+there is no guarantee that the `iterator` functions will complete in order.
+However, the results array will be in the same order as the original `arr`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, transformed)` which must be called once
+ it has completed with an error (which can be `null`) and a transformed item.
+* `callback(err, results)` - *Optional* A callback which is called when all `iterator`
+ functions have finished, or an error occurs. Results is an array of the
+ transformed items from the `arr`.
+
+__Example__
+
+```js
+async.map(['file1','file2','file3'], fs.stat, function(err, results){
+ // results is now an array of stats for each file
+});
+```
+
+__Related__
+* mapSeries(arr, iterator, [callback])
+* mapLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+<a name="select" />
+<a name="filter" />
+### filter(arr, iterator, [callback])
+
+__Alias:__ `select`
+
+Returns a new array of all the values in `arr` which pass an async truth test.
+_The callback for each `iterator` call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`. This operation is
+performed in parallel, but the results array will be in the same order as the
+original.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
+ The `iterator` is passed a `callback(truthValue)`, which must be called with a
+ boolean argument once it has completed.
+* `callback(results)` - *Optional* A callback which is called after all the `iterator`
+ functions have finished.
+
+__Example__
+
+```js
+async.filter(['file1','file2','file3'], fs.exists, function(results){
+ // results now equals an array of the existing files
+});
+```
+
+__Related__
+
+* filterSeries(arr, iterator, [callback])
+* filterLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+<a name="reject" />
+### reject(arr, iterator, [callback])
+
+The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
+
+__Related__
+
+* rejectSeries(arr, iterator, [callback])
+* rejectLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+<a name="reduce" />
+### reduce(arr, memo, iterator, [callback])
+
+__Aliases:__ `inject`, `foldl`
+
+Reduces `arr` into a single value using an async `iterator` to return
+each successive step. `memo` is the initial state of the reduction.
+This function only operates in series.
+
+For performance reasons, it may make sense to split a call to this function into
+a parallel map, and then use the normal `Array.prototype.reduce` on the results.
+This function is for situations where each step in the reduction needs to be async;
+if you can get the data before reducing it, then it's probably a good idea to do so.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `memo` - The initial state of the reduction.
+* `iterator(memo, item, callback)` - A function applied to each item in the
+ array to produce the next step in the reduction. The `iterator` is passed a
+ `callback(err, reduction)` which accepts an optional error as its first
+ argument, and the state of the reduction as the second. If an error is
+ passed to the callback, the reduction is stopped and the main `callback` is
+ immediately called with the error.
+* `callback(err, result)` - *Optional* A callback which is called after all the `iterator`
+ functions have finished. Result is the reduced value.
+
+__Example__
+
+```js
+async.reduce([1,2,3], 0, function(memo, item, callback){
+ // pointless async:
+ process.nextTick(function(){
+ callback(null, memo + item)
+ });
+}, function(err, result){
+ // result is now equal to the last value of memo, which is 6
+});
+```
+
+---------------------------------------
+
+<a name="reduceRight" />
+### reduceRight(arr, memo, iterator, [callback])
+
+__Alias:__ `foldr`
+
+Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
+
+
+---------------------------------------
+
+<a name="detect" />
+### detect(arr, iterator, [callback])
+
+Returns the first value in `arr` that passes an async truth test. The
+`iterator` is applied in parallel, meaning the first iterator to return `true` will
+fire the detect `callback` with that result. That means the result might not be
+the first item in the original `arr` (in terms of order) that passes the test.
+
+If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
+ The iterator is passed a `callback(truthValue)` which must be called with a
+ boolean argument once it has completed. **Note: this callback does not take an error as its first argument.**
+* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns
+ `true`, or after all the `iterator` functions have finished. Result will be
+ the first item in the array that passes the truth test (iterator) or the
+ value `undefined` if none passed. **Note: this callback does not take an error as its first argument.**
+
+__Example__
+
+```js
+async.detect(['file1','file2','file3'], fs.exists, function(result){
+ // result now equals the first file in the list that exists
+});
+```
+
+__Related__
+
+* detectSeries(arr, iterator, [callback])
+* detectLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+<a name="sortBy" />
+### sortBy(arr, iterator, [callback])
+
+Sorts a list by the results of running each `arr` value through an async `iterator`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, sortValue)` which must be called once it
+ has completed with an error (which can be `null`) and a value to use as the sort
+ criteria.
+* `callback(err, results)` - *Optional* A callback which is called after all the `iterator`
+ functions have finished, or an error occurs. Results is the items from
+ the original `arr` sorted by the values returned by the `iterator` calls.
+
+__Example__
+
+```js
+async.sortBy(['file1','file2','file3'], function(file, callback){
+ fs.stat(file, function(err, stats){
+ callback(err, stats.mtime);
+ });
+}, function(err, results){
+ // results is now the original array of files sorted by
+ // modified date
+});
+```
+
+__Sort Order__
+
+By modifying the callback parameter the sorting order can be influenced:
+
+```js
+//ascending order
+async.sortBy([1,9,3,5], function(x, callback){
+ callback(null, x);
+}, function(err,result){
+ //result callback
+} );
+
+//descending order
+async.sortBy([1,9,3,5], function(x, callback){
+ callback(null, x*-1); //<- x*-1 instead of x, turns the order around
+}, function(err,result){
+ //result callback
+} );
+```
+
+---------------------------------------
+
+<a name="some" />
+### some(arr, iterator, [callback])
+
+__Alias:__ `any`
+
+Returns `true` if at least one element in the `arr` satisfies an async test.
+_The callback for each iterator call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`. Once any iterator
+call returns `true`, the main `callback` is immediately called.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in the array
+ in parallel. The iterator is passed a `callback(truthValue)`` which must be
+ called with a boolean argument once it has completed.
+* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns
+ `true`, or after all the iterator functions have finished. Result will be
+ either `true` or `false` depending on the values of the async tests.
+
+ **Note: the callbacks do not take an error as their first argument.**
+__Example__
+
+```js
+async.some(['file1','file2','file3'], fs.exists, function(result){
+ // if result is true then at least one of the files exists
+});
+```
+
+__Related__
+
+* someLimit(arr, limit, iterator, callback)
+
+---------------------------------------
+
+<a name="every" />
+### every(arr, iterator, [callback])
+
+__Alias:__ `all`
+
+Returns `true` if every element in `arr` satisfies an async test.
+_The callback for each `iterator` call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in the array
+ in parallel. The iterator is passed a `callback(truthValue)` which must be
+ called with a boolean argument once it has completed.
+* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns
+ `false`, or after all the iterator functions have finished. Result will be
+ either `true` or `false` depending on the values of the async tests.
+
+ **Note: the callbacks do not take an error as their first argument.**
+
+__Example__
+
+```js
+async.every(['file1','file2','file3'], fs.exists, function(result){
+ // if result is true then every file exists
+});
+```
+
+__Related__
+
+* everyLimit(arr, limit, iterator, callback)
+
+---------------------------------------
+
+<a name="concat" />
+### concat(arr, iterator, [callback])
+
+Applies `iterator` to each item in `arr`, concatenating the results. Returns the
+concatenated list. The `iterator`s are called in parallel, and the results are
+concatenated as they return. There is no guarantee that the results array will
+be returned in the original order of `arr` passed to the `iterator` function.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, results)` which must be called once it
+ has completed with an error (which can be `null`) and an array of results.
+* `callback(err, results)` - *Optional* A callback which is called after all the `iterator`
+ functions have finished, or an error occurs. Results is an array containing
+ the concatenated results of the `iterator` function.
+
+__Example__
+
+```js
+async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
+ // files is now a list of filenames that exist in the 3 directories
+});
+```
+
+__Related__
+
+* concatSeries(arr, iterator, [callback])
+
+
+## Control Flow
+
+<a name="series" />
+### series(tasks, [callback])
+
+Run the functions in the `tasks` array in series, each one running once the previous
+function has completed. If any functions in the series pass an error to its
+callback, no more functions are run, and `callback` is immediately called with the value of the error.
+Otherwise, `callback` receives an array of results when `tasks` have completed.
+
+It is also possible to use an object instead of an array. Each property will be
+run as a function, and the results will be passed to the final `callback` as an object
+instead of an array. This can be a more readable way of handling results from
+[`series`](#series).
+
+**Note** that while many implementations preserve the order of object properties, the
+[ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
+explicitly states that
+
+> The mechanics and order of enumerating the properties is not specified.
+
+So if you rely on the order in which your series of functions are executed, and want
+this to work on all platforms, consider using an array.
+
+__Arguments__
+
+* `tasks` - An array or object containing functions to run, each function is passed
+ a `callback(err, result)` it must call on completion with an error `err` (which can
+ be `null`) and an optional `result` value.
+* `callback(err, results)` - An optional callback to run once all the functions
+ have completed. This function gets a results array (or object) containing all
+ the result arguments passed to the `task` callbacks.
+
+__Example__
+
+```js
+async.series([
+ function(callback){
+ // do some stuff ...
+ callback(null, 'one');
+ },
+ function(callback){
+ // do some more stuff ...
+ callback(null, 'two');
+ }
+],
+// optional callback
+function(err, results){
+ // results is now equal to ['one', 'two']
+});
+
+
+// an example using an object instead of an array
+async.series({
+ one: function(callback){
+ setTimeout(function(){
+ callback(null, 1);
+ }, 200);
+ },
+ two: function(callback){
+ setTimeout(function(){
+ callback(null, 2);
+ }, 100);
+ }
+},
+function(err, results) {
+ // results is now equal to: {one: 1, two: 2}
+});
+```
+
+---------------------------------------
+
+<a name="parallel" />
+### parallel(tasks, [callback])
+
+Run the `tasks` array of functions in parallel, without waiting until the previous
+function has completed. If any of the functions pass an error to its
+callback, the main `callback` is immediately called with the value of the error.
+Once the `tasks` have completed, the results are passed to the final `callback` as an
+array.
+
+**Note:** `parallel` is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded.
+
+It is also possible to use an object instead of an array. Each property will be
+run as a function and the results will be passed to the final `callback` as an object
+instead of an array. This can be a more readable way of handling results from
+[`parallel`](#parallel).
+
+
+__Arguments__
+
+* `tasks` - An array or object containing functions to run. Each function is passed
+ a `callback(err, result)` which it must call on completion with an error `err`
+ (which can be `null`) and an optional `result` value.
+* `callback(err, results)` - An optional callback to run once all the functions
+ have completed successfully. This function gets a results array (or object) containing all
+ the result arguments passed to the task callbacks.
+
+__Example__
+
+```js
+async.parallel([
+ function(callback){
+ setTimeout(function(){
+ callback(null, 'one');
+ }, 200);
+ },
+ function(callback){
+ setTimeout(function(){
+ callback(null, 'two');
+ }, 100);
+ }
+],
+// optional callback
+function(err, results){
+ // the results array will equal ['one','two'] even though
+ // the second function had a shorter timeout.
+});
+
+
+// an example using an object instead of an array
+async.parallel({
+ one: function(callback){
+ setTimeout(function(){
+ callback(null, 1);
+ }, 200);
+ },
+ two: function(callback){
+ setTimeout(function(){
+ callback(null, 2);
+ }, 100);
+ }
+},
+function(err, results) {
+ // results is now equals to: {one: 1, two: 2}
+});
+```
+
+__Related__
+
+* parallelLimit(tasks, limit, [callback])
+
+---------------------------------------
+
+<a name="whilst" />
+### whilst(test, fn, callback)
+
+Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
+or an error occurs.
+
+__Arguments__
+
+* `test()` - synchronous truth test to perform before each execution of `fn`.
+* `fn(callback)` - A function which is called each time `test` passes. The function is
+ passed a `callback(err)`, which must be called once it has completed with an
+ optional `err` argument.
+* `callback(err, [results])` - A callback which is called after the test
+ function has failed and repeated execution of `fn` has stopped. `callback`
+ will be passed an error and any arguments passed to the final `fn`'s callback.
+
+__Example__
+
+```js
+var count = 0;
+
+async.whilst(
+ function () { return count < 5; },
+ function (callback) {
+ count++;
+ setTimeout(function () {
+ callback(null, count);
+ }, 1000);
+ },
+ function (err, n) {
+ // 5 seconds have passed, n = 5
+ }
+);
+```
+
+---------------------------------------
+
+<a name="doWhilst" />
+### doWhilst(fn, test, callback)
+
+The post-check version of [`whilst`](#whilst). To reflect the difference in
+the order of operations, the arguments `test` and `fn` are switched.
+
+`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
+
+---------------------------------------
+
+<a name="until" />
+### until(test, fn, callback)
+
+Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
+or an error occurs. `callback` will be passed an error and any arguments passed
+to the final `fn`'s callback.
+
+The inverse of [`whilst`](#whilst).
+
+---------------------------------------
+
+<a name="doUntil" />
+### doUntil(fn, test, callback)
+
+Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
+
+---------------------------------------
+
+<a name="during" />
+### during(test, fn, callback)
+
+Like [`whilst`](#whilst), except the `test` is an asynchronous function that is passed a callback in the form of `function (err, truth)`. If error is passed to `test` or `fn`, the main callback is immediately called with the value of the error.
+
+__Example__
+
+```js
+var count = 0;
+
+async.during(
+ function (callback) {
+ return callback(null, count < 5);
+ },
+ function (callback) {
+ count++;
+ setTimeout(callback, 1000);
+ },
+ function (err) {
+ // 5 seconds have passed
+ }
+);
+```
+
+---------------------------------------
+
+<a name="doDuring" />
+### doDuring(fn, test, callback)
+
+The post-check version of [`during`](#during). To reflect the difference in
+the order of operations, the arguments `test` and `fn` are switched.
+
+Also a version of [`doWhilst`](#doWhilst) with asynchronous `test` function.
+
+---------------------------------------
+
+<a name="forever" />
+### forever(fn, [errback])
+
+Calls the asynchronous function `fn` with a callback parameter that allows it to
+call itself again, in series, indefinitely.
+
+If an error is passed to the callback then `errback` is called with the
+error, and execution stops, otherwise it will never be called.
+
+```js
+async.forever(
+ function(next) {
+ // next is suitable for passing to things that need a callback(err [, whatever]);
+ // it will result in this function being called again.
+ },
+ function(err) {
+ // if next is called with a value in its first parameter, it will appear
+ // in here as 'err', and execution will stop.
+ }
+);
+```
+
+---------------------------------------
+
+<a name="waterfall" />
+### waterfall(tasks, [callback])
+
+Runs the `tasks` array of functions in series, each passing their results to the next in
+the array. However, if any of the `tasks` pass an error to their own callback, the
+next function is not executed, and the main `callback` is immediately called with
+the error.
+
+__Arguments__
+
+* `tasks` - An array of functions to run, each function is passed a
+ `callback(err, result1, result2, ...)` it must call on completion. The first
+ argument is an error (which can be `null`) and any further arguments will be
+ passed as arguments in order to the next task.
+* `callback(err, [results])` - An optional callback to run once all the functions
+ have completed. This will be passed the results of the last task's callback.
+
+
+
+__Example__
+
+```js
+async.waterfall([
+ function(callback) {
+ callback(null, 'one', 'two');
+ },
+ function(arg1, arg2, callback) {
+ // arg1 now equals 'one' and arg2 now equals 'two'
+ callback(null, 'three');
+ },
+ function(arg1, callback) {
+ // arg1 now equals 'three'
+ callback(null, 'done');
+ }
+], function (err, result) {
+ // result now equals 'done'
+});
+```
+
+---------------------------------------
+<a name="compose" />
+### compose(fn1, fn2...)
+
+Creates a function which is a composition of the passed asynchronous
+functions. Each function consumes the return value of the function that
+follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
+`f(g(h()))`, only this version uses callbacks to obtain the return values.
+
+Each function is executed with the `this` binding of the composed function.
+
+__Arguments__
+
+* `functions...` - the asynchronous functions to compose
+
+
+__Example__
+
+```js
+function add1(n, callback) {
+ setTimeout(function () {
+ callback(null, n + 1);
+ }, 10);
+}
+
+function mul3(n, callback) {
+ setTimeout(function () {
+ callback(null, n * 3);
+ }, 10);
+}
+
+var add1mul3 = async.compose(mul3, add1);
+
+add1mul3(4, function (err, result) {
+ // result now equals 15
+});
+```
+
+---------------------------------------
+<a name="seq" />
+### seq(fn1, fn2...)
+
+Version of the compose function that is more natural to read.
+Each function consumes the return value of the previous function.
+It is the equivalent of [`compose`](#compose) with the arguments reversed.
+
+Each function is executed with the `this` binding of the composed function.
+
+__Arguments__
+
+* `functions...` - the asynchronous functions to compose
+
+
+__Example__
+
+```js
+// Requires lodash (or underscore), express3 and dresende's orm2.
+// Part of an app, that fetches cats of the logged user.
+// This example uses `seq` function to avoid overnesting and error
+// handling clutter.
+app.get('/cats', function(request, response) {
+ var User = request.models.User;
+ async.seq(
+ _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
+ function(user, fn) {
+ user.getCats(fn); // 'getCats' has signature (callback(err, data))
+ }
+ )(req.session.user_id, function (err, cats) {
+ if (err) {
+ console.error(err);
+ response.json({ status: 'error', message: err.message });
+ } else {
+ response.json({ status: 'ok', message: 'Cats found', data: cats });
+ }
+ });
+});
+```
+
+---------------------------------------
+<a name="applyEach" />
+### applyEach(fns, args..., callback)
+
+Applies the provided arguments to each function in the array, calling
+`callback` after all functions have completed. If you only provide the first
+argument, then it will return a function which lets you pass in the
+arguments as if it were a single function call.
+
+__Arguments__
+
+* `fns` - the asynchronous functions to all call with the same arguments
+* `args...` - any number of separate arguments to pass to the function
+* `callback` - the final argument should be the callback, called when all
+ functions have completed processing
+
+
+__Example__
+
+```js
+async.applyEach([enableSearch, updateSchema], 'bucket', callback);
+
+// partial application example:
+async.each(
+ buckets,
+ async.applyEach([enableSearch, updateSchema]),
+ callback
+);
+```
+
+__Related__
+
+* applyEachSeries(tasks, args..., [callback])
+
+---------------------------------------
+
+<a name="queue" />
+### queue(worker, [concurrency])
+
+Creates a `queue` object with the specified `concurrency`. Tasks added to the
+`queue` are processed in parallel (up to the `concurrency` limit). If all
+`worker`s are in progress, the task is queued until one becomes available.
+Once a `worker` completes a `task`, that `task`'s callback is called.
+
+__Arguments__
+
+* `worker(task, callback)` - An asynchronous function for processing a queued
+ task, which must call its `callback(err)` argument when finished, with an
+ optional `error` as an argument. If you want to handle errors from an individual task, pass a callback to `q.push()`.
+* `concurrency` - An `integer` for determining how many `worker` functions should be
+ run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown.
+
+__Queue objects__
+
+The `queue` object returned by this function has the following properties and
+methods:
+
+* `length()` - a function returning the number of items waiting to be processed.
+* `started` - a function returning whether or not any items have been pushed and processed by the queue
+* `running()` - a function returning the number of items currently being processed.
+* `workersList()` - a function returning the array of items currently being processed.
+* `idle()` - a function returning false if there are items waiting or being processed, or true if not.
+* `concurrency` - an integer for determining how many `worker` functions should be
+ run in parallel. This property can be changed after a `queue` is created to
+ alter the concurrency on-the-fly.
+* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
+ the `worker` has finished processing the task. Instead of a single task, a `tasks` array
+ can be submitted. The respective callback is used for every task in the list.
+* `unshift(task, [callback])` - add a new task to the front of the `queue`.
+* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
+ and further tasks will be queued.
+* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
+* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
+* `paused` - a boolean for determining whether the queue is in a paused state
+* `pause()` - a function that pauses the processing of tasks until `resume()` is called.
+* `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
+* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle.
+
+__Example__
+
+```js
+// create a queue object with concurrency 2
+
+var q = async.queue(function (task, callback) {
+ console.log('hello ' + task.name);
+ callback();
+}, 2);
+
+
+// assign a callback
+q.drain = function() {
+ console.log('all items have been processed');
+}
+
+// add some items to the queue
+
+q.push({name: 'foo'}, function (err) {
+ console.log('finished processing foo');
+});
+q.push({name: 'bar'}, function (err) {
+ console.log('finished processing bar');
+});
+
+// add some items to the queue (batch-wise)
+
+q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
+ console.log('finished processing item');
+});
+
+// add some items to the front of the queue
+
+q.unshift({name: 'bar'}, function (err) {
+ console.log('finished processing bar');
+});
+```
+
+
+---------------------------------------
+
+<a name="priorityQueue" />
+### priorityQueue(worker, concurrency)
+
+The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects:
+
+* `push(task, priority, [callback])` - `priority` should be a number. If an array of
+ `tasks` is given, all tasks will be assigned the same priority.
+* The `unshift` method was removed.
+
+---------------------------------------
+
+<a name="cargo" />
+### cargo(worker, [payload])
+
+Creates a `cargo` object with the specified payload. Tasks added to the
+cargo will be processed altogether (up to the `payload` limit). If the
+`worker` is in progress, the task is queued until it becomes available. Once
+the `worker` has completed some tasks, each callback of those tasks is called.
+Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work.
+
+While [queue](#queue) passes only one task to one of a group of workers
+at a time, cargo passes an array of tasks to a single worker, repeating
+when the worker is finished.
+
+__Arguments__
+
+* `worker(tasks, callback)` - An asynchronous function for processing an array of
+ queued tasks, which must call its `callback(err)` argument when finished, with
+ an optional `err` argument.
+* `payload` - An optional `integer` for determining how many tasks should be
+ processed per round; if omitted, the default is unlimited.
+
+__Cargo objects__
+
+The `cargo` object returned by this function has the following properties and
+methods:
+
+* `length()` - A function returning the number of items waiting to be processed.
+* `payload` - An `integer` for determining how many tasks should be
+ process per round. This property can be changed after a `cargo` is created to
+ alter the payload on-the-fly.
+* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
+ once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
+ can be submitted. The respective callback is used for every task in the list.
+* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
+* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
+* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
+* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue)
+
+__Example__
+
+```js
+// create a cargo object with payload 2
+
+var cargo = async.cargo(function (tasks, callback) {
+ for(var i=0; i<tasks.length; i++){
+ console.log('hello ' + tasks[i].name);
+ }
+ callback();
+}, 2);
+
+
+// add some items
+
+cargo.push({name: 'foo'}, function (err) {
+ console.log('finished processing foo');
+});
+cargo.push({name: 'bar'}, function (err) {
+ console.log('finished processing bar');
+});
+cargo.push({name: 'baz'}, function (err) {
+ console.log('finished processing baz');
+});
+```
+
+---------------------------------------
+
+<a name="auto" />
+### auto(tasks, [concurrency], [callback])
+
+Determines the best order for running the functions in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied.
+
+If any of the functions pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error. Functions also receive an object containing the results of functions which have completed so far.
+
+Note, all functions are called with a `results` object as a second argument,
+so it is unsafe to pass functions in the `tasks` object which cannot handle the
+extra argument.
+
+For example, this snippet of code:
+
+```js
+async.auto({
+ readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
+}, callback);
+```
+
+will have the effect of calling `readFile` with the results object as the last
+argument, which will fail:
+
+```js
+fs.readFile('data.txt', 'utf-8', cb, {});
+```
+
+Instead, wrap the call to `readFile` in a function which does not forward the
+`results` object:
+
+```js
+async.auto({
+ readData: function(cb, results){
+ fs.readFile('data.txt', 'utf-8', cb);
+ }
+}, callback);
+```
+
+__Arguments__
+
+* `tasks` - An object. Each of its properties is either a function or an array of
+ requirements, with the function itself the last item in the array. The object's key
+ of a property serves as the name of the task defined by that property,
+ i.e. can be used when specifying requirements for other tasks.
+ The function receives two arguments: (1) a `callback(err, result)` which must be
+ called when finished, passing an `error` (which can be `null`) and the result of
+ the function's execution, and (2) a `results` object, containing the results of
+ the previously executed functions.
+* `concurrency` - An optional `integer` for determining the maximum number of tasks that can be run in parallel. By default, as many as possible.
+* `callback(err, results)` - An optional callback which is called when all the
+ tasks have been completed. It receives the `err` argument if any `tasks`
+ pass an error to their callback. Results are always returned; however, if
+ an error occurs, no further `tasks` will be performed, and the results
+ object will only contain partial results.
+
+
+__Example__
+
+```js
+async.auto({
+ get_data: function(callback){
+ console.log('in get_data');
+ // async code to get some data
+ callback(null, 'data', 'converted to array');
+ },
+ make_folder: function(callback){
+ console.log('in make_folder');
+ // async code to create a directory to store a file in
+ // this is run at the same time as getting the data
+ callback(null, 'folder');
+ },
+ write_file: ['get_data', 'make_folder', function(callback, results){
+ console.log('in write_file', JSON.stringify(results));
+ // once there is some data and the directory exists,
+ // write the data to a file in the directory
+ callback(null, 'filename');
+ }],
+ email_link: ['write_file', function(callback, results){
+ console.log('in email_link', JSON.stringify(results));
+ // once the file is written let's email a link to it...
+ // results.write_file contains the filename returned by write_file.
+ callback(null, {'file':results.write_file, 'email':'user@example.com'});
+ }]
+}, function(err, results) {
+ console.log('err = ', err);
+ console.log('results = ', results);
+});
+```
+
+This is a fairly trivial example, but to do this using the basic parallel and
+series functions would look like this:
+
+```js
+async.parallel([
+ function(callback){
+ console.log('in get_data');
+ // async code to get some data
+ callback(null, 'data', 'converted to array');
+ },
+ function(callback){
+ console.log('in make_folder');
+ // async code to create a directory to store a file in
+ // this is run at the same time as getting the data
+ callback(null, 'folder');
+ }
+],
+function(err, results){
+ async.series([
+ function(callback){
+ console.log('in write_file', JSON.stringify(results));
+ // once there is some data and the directory exists,
+ // write the data to a file in the directory
+ results.push('filename');
+ callback(null);
+ },
+ function(callback){
+ console.log('in email_link', JSON.stringify(results));
+ // once the file is written let's email a link to it...
+ callback(null, {'file':results.pop(), 'email':'user@example.com'});
+ }
+ ]);
+});
+```
+
+For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
+new tasks much easier (and the code more readable).
+
+
+---------------------------------------
+
+<a name="retry" />
+### retry([opts = {times: 5, interval: 0}| 5], task, [callback])
+
+Attempts to get a successful response from `task` no more than `times` times before
+returning an error. If the task is successful, the `callback` will be passed the result
+of the successful task. If all attempts fail, the callback will be passed the error and
+result (if any) of the final attempt.
+
+__Arguments__
+
+* `opts` - Can be either an object with `times` and `interval` or a number. `times` is how many attempts should be made before giving up. `interval` is how long to wait inbetween attempts. Defaults to {times: 5, interval: 0}
+ * if a number is passed in it sets `times` only (with `interval` defaulting to 0).
+* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
+ which must be called when finished, passing `err` (which can be `null`) and the `result` of
+ the function's execution, and (2) a `results` object, containing the results of
+ the previously executed functions (if nested inside another control flow).
+* `callback(err, results)` - An optional callback which is called when the
+ task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.
+
+The [`retry`](#retry) function can be used as a stand-alone control flow by passing a
+callback, as shown below:
+
+```js
+async.retry(3, apiMethod, function(err, result) {
+ // do something with the result
+});
+```
+
+```js
+async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
+ // do something with the result
+});
+```
+
+It can also be embedded within other control flow functions to retry individual methods
+that are not as reliable, like this:
+
+```js
+async.auto({
+ users: api.getUsers.bind(api),
+ payments: async.retry(3, api.getPayments.bind(api))
+}, function(err, results) {
+ // do something with the results
+});
+```
+
+
+---------------------------------------
+
+<a name="iterator" />
+### iterator(tasks)
+
+Creates an iterator function which calls the next function in the `tasks` array,
+returning a continuation to call the next one after that. It's also possible to
+“peek” at the next iterator with `iterator.next()`.
+
+This function is used internally by the `async` module, but can be useful when
+you want to manually control the flow of functions in series.
+
+__Arguments__
+
+* `tasks` - An array of functions to run.
+
+__Example__
+
+```js
+var iterator = async.iterator([
+ function(){ sys.p('one'); },
+ function(){ sys.p('two'); },
+ function(){ sys.p('three'); }
+]);
+
+node> var iterator2 = iterator();
+'one'
+node> var iterator3 = iterator2();
+'two'
+node> iterator3();
+'three'
+node> var nextfn = iterator2.next();
+node> nextfn();
+'three'
+```
+
+---------------------------------------
+
+<a name="apply" />
+### apply(function, arguments..)
+
+Creates a continuation function with some arguments already applied.
+
+Useful as a shorthand when combined with other control flow functions. Any arguments
+passed to the returned function are added to the arguments originally passed
+to apply.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to automatically apply when the
+ continuation is called.
+
+__Example__
+
+```js
+// using apply
+
+async.parallel([
+ async.apply(fs.writeFile, 'testfile1', 'test1'),
+ async.apply(fs.writeFile, 'testfile2', 'test2'),
+]);
+
+
+// the same process without using apply
+
+async.parallel([
+ function(callback){
+ fs.writeFile('testfile1', 'test1', callback);
+ },
+ function(callback){
+ fs.writeFile('testfile2', 'test2', callback);
+ }
+]);
+```
+
+It's possible to pass any number of additional arguments when calling the
+continuation:
+
+```js
+node> var fn = async.apply(sys.puts, 'one');
+node> fn('two', 'three');
+one
+two
+three
+```
+
+---------------------------------------
+
+<a name="nextTick" />
+### nextTick(callback), setImmediate(callback)
+
+Calls `callback` on a later loop around the event loop. In Node.js this just
+calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`
+if available, otherwise `setTimeout(callback, 0)`, which means other higher priority
+events may precede the execution of `callback`.
+
+This is used internally for browser-compatibility purposes.
+
+__Arguments__
+
+* `callback` - The function to call on a later loop around the event loop.
+
+__Example__
+
+```js
+var call_order = [];
+async.nextTick(function(){
+ call_order.push('two');
+ // call_order now equals ['one','two']
+});
+call_order.push('one')
+```
+
+<a name="times" />
+### times(n, iterator, [callback])
+
+Calls the `iterator` function `n` times, and accumulates results in the same manner
+you would use with [`map`](#map).
+
+__Arguments__
+
+* `n` - The number of times to run the function.
+* `iterator` - The function to call `n` times.
+* `callback` - see [`map`](#map)
+
+__Example__
+
+```js
+// Pretend this is some complicated async factory
+var createUser = function(id, callback) {
+ callback(null, {
+ id: 'user' + id
+ })
+}
+// generate 5 users
+async.times(5, function(n, next){
+ createUser(n, function(err, user) {
+ next(err, user)
+ })
+}, function(err, users) {
+ // we should now have 5 users
+});
+```
+
+__Related__
+
+* timesSeries(n, iterator, [callback])
+* timesLimit(n, limit, iterator, [callback])
+
+
+## Utils
+
+<a name="memoize" />
+### memoize(fn, [hasher])
+
+Caches the results of an `async` function. When creating a hash to store function
+results against, the callback is omitted from the hash and an optional hash
+function can be used.
+
+If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function.
+
+The cache of results is exposed as the `memo` property of the function returned
+by `memoize`.
+
+__Arguments__
+
+* `fn` - The function to proxy and cache results from.
+* `hasher` - An optional function for generating a custom hash for storing
+ results. It has all the arguments applied to it apart from the callback, and
+ must be synchronous.
+
+__Example__
+
+```js
+var slow_fn = function (name, callback) {
+ // do something
+ callback(null, result);
+};
+var fn = async.memoize(slow_fn);
+
+// fn can now be used as if it were slow_fn
+fn('some name', function () {
+ // callback
+});
+```
+
+<a name="unmemoize" />
+### unmemoize(fn)
+
+Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
+form. Handy for testing.
+
+__Arguments__
+
+* `fn` - the memoized function
+
+---------------------------------------
+
+<a name="ensureAsync" />
+### ensureAsync(fn)
+
+Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained.
+
+__Arguments__
+
+* `fn` - an async function, one that expects a node-style callback as its last argument
+
+Returns a wrapped function with the exact same call signature as the function passed in.
+
+__Example__
+
+```js
+function sometimesAsync(arg, callback) {
+ if (cache[arg]) {
+ return callback(null, cache[arg]); // this would be synchronous!!
+ } else {
+ doSomeIO(arg, callback); // this IO would be asynchronous
+ }
+}
+
+// this has a risk of stack overflows if many results are cached in a row
+async.mapSeries(args, sometimesAsync, done);
+
+// this will defer sometimesAsync's callback if necessary,
+// preventing stack overflows
+async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
+
+```
+
+---------------------------------------
+
+<a name="constant">
+### constant(values...)
+
+Returns a function that when called, calls-back with the values provided. Useful as the first function in a `waterfall`, or for plugging values in to `auto`.
+
+__Example__
+
+```js
+async.waterfall([
+ async.constant(42),
+ function (value, next) {
+ // value === 42
+ },
+ //...
+], callback);
+
+async.waterfall([
+ async.constant(filename, "utf8"),
+ fs.readFile,
+ function (fileData, next) {
+ //...
+ }
+ //...
+], callback);
+
+async.auto({
+ hostname: async.constant("https://server.net/"),
+ port: findFreePort,
+ launchServer: ["hostname", "port", function (cb, options) {
+ startServer(options, cb);
+ }],
+ //...
+}, callback);
+
+```
+
+---------------------------------------
+
+<a name="asyncify">
+<a name="wrapSync">
+### asyncify(func)
+
+__Alias:__ `wrapSync`
+
+Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback.
+
+__Example__
+
+```js
+async.waterfall([
+ async.apply(fs.readFile, filename, "utf8"),
+ async.asyncify(JSON.parse),
+ function (data, next) {
+ // data is the result of parsing the text.
+ // If there was a parsing error, it would have been caught.
+ }
+], callback)
+```
+
+---------------------------------------
+
+<a name="log" />
+### log(function, arguments)
+
+Logs the result of an `async` function to the `console`. Only works in Node.js or
+in browsers that support `console.log` and `console.error` (such as FF and Chrome).
+If multiple arguments are returned from the async function, `console.log` is
+called on each argument in order.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to apply to the function.
+
+__Example__
+
+```js
+var hello = function(name, callback){
+ setTimeout(function(){
+ callback(null, 'hello ' + name);
+ }, 1000);
+};
+```
+```js
+node> async.log(hello, 'world');
+'hello world'
+```
+
+---------------------------------------
+
+<a name="dir" />
+### dir(function, arguments)
+
+Logs the result of an `async` function to the `console` using `console.dir` to
+display the properties of the resulting object. Only works in Node.js or
+in browsers that support `console.dir` and `console.error` (such as FF and Chrome).
+If multiple arguments are returned from the async function, `console.dir` is
+called on each argument in order.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to apply to the function.
+
+__Example__
+
+```js
+var hello = function(name, callback){
+ setTimeout(function(){
+ callback(null, {hello: name});
+ }, 1000);
+};
+```
+```js
+node> async.dir(hello, 'world');
+{hello: 'world'}
+```
+
+---------------------------------------
+
+<a name="noConflict" />
+### noConflict()
+
+Changes the value of `async` back to its original value, returning a reference to the
+`async` object.
diff --git a/build/async.js b/build/async.js
index 84513d7..e5d60e3 100644
--- a/build/async.js
+++ b/build/async.js
@@ -1,10 +1,31 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
- factory((global.async = {}));
+ (factory((global.async = {})));
}(this, function (exports) { 'use strict';
/**
+ * A faster alternative to `Function#apply`, this function invokes `func`
+ * with the `this` binding of `thisArg` and the arguments of `args`.
+ *
+ * @private
+ * @param {Function} func The function to invoke.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {...*} [args] The arguments to invoke `func` with.
+ * @returns {*} Returns the result of `func`.
+ */
+ function apply$1(func, thisArg, args) {
+ var length = args ? args.length : 0;
+ switch (length) {
+ case 0: return func.call(thisArg);
+ case 1: return func.call(thisArg, args[0]);
+ case 2: return func.call(thisArg, args[0], args[1]);
+ case 3: return func.call(thisArg, args[0], args[1], args[2]);
+ }
+ return func.apply(thisArg, args);
+ }
+
+ /**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
@@ -34,27 +55,6 @@
return !!value && (type == 'object' || type == 'function');
}
- /**
- * A faster alternative to `Function#apply`, this function invokes `func`
- * with the `this` binding of `thisArg` and the arguments of `args`.
- *
- * @private
- * @param {Function} func The function to invoke.
- * @param {*} thisArg The `this` binding of `func`.
- * @param {...*} [args] The arguments to invoke `func` with.
- * @returns {*} Returns the result of `func`.
- */
- function apply$1(func, thisArg, args) {
- var length = args ? args.length : 0;
- switch (length) {
- case 0: return func.call(thisArg);
- case 1: return func.call(thisArg, args[0]);
- case 2: return func.call(thisArg, args[0], args[1]);
- case 3: return func.call(thisArg, args[0], args[1], args[2]);
- }
- return func.apply(thisArg, args);
- }
-
var funcTag = '[object Function]';
var genTag = '[object GeneratorFunction]';
/** Used for built-in method references. */
@@ -241,77 +241,23 @@
};
}
- function asyncify(func) {
- return rest(function (args) {
- var callback = args.pop();
- var result;
- try {
- result = func.apply(this, args);
- } catch (e) {
- return callback(e);
- }
- // if result is Promise object
- if (isObject(result) && typeof result.then === 'function') {
- result.then(function (value) {
- callback(null, value);
- })['catch'](function (err) {
- callback(err.message ? err : new Error(err));
- });
+ function applyEach$1(eachfn) {
+ return rest(function (fns, args) {
+ var go = rest(function (args) {
+ var that = this;
+ var callback = args.pop();
+ return eachfn(fns, function (fn, _, cb) {
+ fn.apply(that, args.concat([cb]));
+ }, callback);
+ });
+ if (args.length) {
+ return go.apply(this, args);
} else {
- callback(null, result);
+ return go;
}
});
}
- /**
- * A specialized version of `_.map` for arrays without support for iteratee
- * shorthands.
- *
- * @private
- * @param {Array} array The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the new mapped array.
- */
- function arrayMap(array, iteratee) {
- var index = -1,
- length = array.length,
- result = Array(length);
-
- while (++index < length) {
- result[index] = iteratee(array[index], index, array);
- }
- return result;
- }
-
- /**
- * The base implementation of `_.property` without support for deep paths.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @returns {Function} Returns the new function.
- */
- function baseProperty(key) {
- return function(object) {
- return object == null ? undefined : object[key];
- };
- }
-
- function _filter(eachfn, arr, iterator, callback) {
- var results = [];
- eachfn(arr, function (x, index, callback) {
- iterator(x, function (v) {
- if (v) {
- results.push({ index: index, value: x });
- }
- callback();
- });
- }, function () {
- callback(arrayMap(results.sort(function (a, b) {
- return a.index - b.index;
- }), baseProperty('value')));
- });
- }
-
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT$1 = 'Expected a function';
@@ -388,6 +334,19 @@
}
/**
+ * The base implementation of `_.property` without support for deep paths.
+ *
+ * @private
+ * @param {string} key The key of the property to get.
+ * @returns {Function} Returns the new function.
+ */
+ function baseProperty(key) {
+ return function(object) {
+ return object == null ? undefined : object[key];
+ };
+ }
+
+ /**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
@@ -799,6 +758,36 @@
};
}
+ function eachOf(object, iterator, callback) {
+ callback = once(callback || noop);
+ object = object || [];
+
+ var iter = keyIterator(object);
+ var key,
+ completed = 0;
+
+ while ((key = iter()) != null) {
+ completed += 1;
+ iterator(object[key], key, onlyOnce(done));
+ }
+
+ if (completed === 0) callback(null);
+
+ function done(err) {
+ completed--;
+ if (err) {
+ callback(err);
+ }
+ // Check key is null in case iterator isn't exhausted
+ // and done resolved synchronously.
+ else if (key === null && completed <= 0) {
+ callback(null);
+ }
+ }
+ }
+
+ var applyEach = applyEach$1(eachOf);
+
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay;
@@ -849,137 +838,126 @@
iterate();
}
- function doSeries(fn) {
- return function (obj, iterator, callback) {
- return fn(eachOfSeries, obj, iterator, callback);
- };
- }
+ var applyEachSeries = applyEach$1(eachOfSeries);
- var filterSeries = doSeries(_filter);
+ var apply = rest(function (fn, args) {
+ return rest(function (callArgs) {
+ return fn.apply(null, args.concat(callArgs));
+ });
+ });
- function _eachOfLimit(limit) {
- return function (obj, iterator, callback) {
- callback = once(callback || noop);
- obj = obj || [];
- var nextKey = keyIterator(obj);
- if (limit <= 0) {
- return callback(null);
+ function asyncify(func) {
+ return rest(function (args) {
+ var callback = args.pop();
+ var result;
+ try {
+ result = func.apply(this, args);
+ } catch (e) {
+ return callback(e);
}
- var done = false;
- var running = 0;
- var errored = false;
-
- (function replenish() {
- if (done && running <= 0) {
- return callback(null);
- }
-
- while (running < limit && !errored) {
- var key = nextKey();
- if (key === null) {
- done = true;
- if (running <= 0) {
- callback(null);
- }
- return;
- }
- running += 1;
- iterator(obj[key], key, onlyOnce(function (err) {
- running -= 1;
- if (err) {
- callback(err);
- errored = true;
- } else {
- replenish();
- }
- }));
- }
- })();
- };
- }
-
- function doParallelLimit(fn) {
- return function (obj, limit, iterator, callback) {
- return fn(_eachOfLimit(limit), obj, iterator, callback);
- };
- }
-
- var filterLimit = doParallelLimit(_filter);
-
- function eachOf(object, iterator, callback) {
- callback = once(callback || noop);
- object = object || [];
-
- var iter = keyIterator(object);
- var key,
- completed = 0;
-
- while ((key = iter()) != null) {
- completed += 1;
- iterator(object[key], key, onlyOnce(done));
- }
-
- if (completed === 0) callback(null);
-
- function done(err) {
- completed--;
- if (err) {
- callback(err);
+ // if result is Promise object
+ if (isObject(result) && typeof result.then === 'function') {
+ result.then(function (value) {
+ callback(null, value);
+ })['catch'](function (err) {
+ callback(err.message ? err : new Error(err));
+ });
+ } else {
+ callback(null, result);
}
- // Check key is null in case iterator isn't exhausted
- // and done resolved synchronously.
- else if (key === null && completed <= 0) {
- callback(null);
- }
- }
- }
-
- function doParallel(fn) {
- return function (obj, iterator, callback) {
- return fn(eachOf, obj, iterator, callback);
- };
- }
-
- var filter = doParallel(_filter);
-
- function reduce(arr, memo, iterator, cb) {
- eachOfSeries(arr, function (x, i, cb) {
- iterator(memo, x, function (err, v) {
- memo = v;
- cb(err);
- });
- }, function (err) {
- cb(err, memo);
});
}
- var slice = Array.prototype.slice;
+ /**
+ * A specialized version of `_.forEach` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayEach(array, iteratee) {
+ var index = -1,
+ length = array.length;
- function reduceRight(arr, memo, iterator, cb) {
- var reversed = slice.call(arr).reverse();
- reduce(reversed, memo, iterator, cb);
+ while (++index < length) {
+ if (iteratee(array[index], index, array) === false) {
+ break;
+ }
+ }
+ return array;
}
- function eachOfLimit(obj, limit, iterator, cb) {
- _eachOfLimit(limit)(obj, iterator, cb);
- }
+ /**
+ * A specialized version of `_.every` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check, else `false`.
+ */
+ function arrayEvery(array, predicate) {
+ var index = -1,
+ length = array.length;
- function _withoutIndex(iterator) {
- return function (value, index, callback) {
- return iterator(value, callback);
- };
+ while (++index < length) {
+ if (!predicate(array[index], index, array)) {
+ return false;
+ }
+ }
+ return true;
}
- function eachLimit(arr, limit, iterator, cb) {
- return _eachOfLimit(limit)(arr, _withoutIndex(iterator), cb);
- }
+ /**
+ * Creates a base function for methods like `_.forIn`.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
+ function createBaseFor(fromRight) {
+ return function(object, iteratee, keysFunc) {
+ var index = -1,
+ iterable = Object(object),
+ props = keysFunc(object),
+ length = props.length;
- function eachSeries(arr, iterator, cb) {
- return eachOfSeries(arr, _withoutIndex(iterator), cb);
+ while (length--) {
+ var key = props[fromRight ? length : ++index];
+ if (iteratee(iterable[key], key, iterable) === false) {
+ break;
+ }
+ }
+ return object;
+ };
}
- function each(arr, iterator, cb) {
- return eachOf(arr, _withoutIndex(iterator), cb);
+ /**
+ * The base implementation of `baseForIn` and `baseForOwn` which iterates
+ * over `object` properties returned by `keysFunc` invoking `iteratee` for
+ * each property. Iteratee functions may exit iteration early by explicitly
+ * returning `false`.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @returns {Object} Returns `object`.
+ */
+ var baseFor = createBaseFor();
+
+ /**
+ * The base implementation of `_.forOwn` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ */
+ function baseForOwn(object, iteratee) {
+ return object && baseFor(object, iteratee, keys);
}
/**
@@ -1001,362 +979,241 @@
return value;
}
- function _createTester(eachfn, check, getResult) {
- return function (arr, limit, iterator, cb) {
- function done() {
- if (cb) cb(getResult(false, void 0));
- }
- function iteratee(x, _, callback) {
- if (!cb) return callback();
- iterator(x, function (v) {
- if (cb && check(v)) {
- cb(getResult(true, x));
- cb = iterator = false;
- }
- callback();
- });
- }
- if (arguments.length > 3) {
- eachfn(arr, limit, iteratee, done);
- } else {
- cb = iterator;
- iterator = limit;
- eachfn(arr, iteratee, done);
- }
- };
- }
-
- var some = _createTester(eachOf, Boolean, identity);
-
- function notId(v) {
- return !v;
- }
-
- var every = _createTester(eachOf, notId, notId);
-
- function whilst(test, iterator, cb) {
- cb = cb || noop;
- if (!test()) return cb(null);
- var next = rest(function (err, args) {
- if (err) return cb(err);
- if (test.apply(this, args)) return iterator(next);
- cb.apply(null, [null].concat(args));
- });
- iterator(next);
- }
-
- function ensureAsync(fn) {
- return rest(function (args) {
- var callback = args.pop();
- var sync = true;
- args.push(function () {
- var innerArgs = arguments;
- if (sync) {
- setImmediate$1(function () {
- callback.apply(null, innerArgs);
- });
- } else {
- callback.apply(null, innerArgs);
- }
- });
- fn.apply(this, args);
- sync = false;
- });
- }
-
- function iterator (tasks) {
- function makeCallback(index) {
- function fn() {
- if (tasks.length) {
- tasks[index].apply(null, arguments);
- }
- return fn.next();
- }
- fn.next = function () {
- return index < tasks.length - 1 ? makeCallback(index + 1) : null;
- };
- return fn;
- }
- return makeCallback(0);
- }
-
- function waterfall (tasks, cb) {
- cb = once(cb || noop);
- if (!isArray(tasks)) return cb(new Error('First argument to waterfall must be an array of functions'));
- if (!tasks.length) return cb();
-
- function wrapIterator(iterator) {
- return rest(function (err, args) {
- if (err) {
- cb.apply(null, [err].concat(args));
- } else {
- var next = iterator.next();
- if (next) {
- args.push(wrapIterator(next));
- } else {
- args.push(cb);
- }
- ensureAsync(iterator).apply(null, args);
- }
- });
- }
- wrapIterator(iterator(tasks))();
+ /**
+ * Converts `value` to a function if it's not one.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {Function} Returns the function.
+ */
+ function toFunction(value) {
+ return typeof value == 'function' ? value : identity;
}
- function until(test, iterator, cb) {
- return whilst(function () {
- return !test.apply(this, arguments);
- }, iterator, cb);
+ /**
+ * Iterates over own enumerable properties of an object invoking `iteratee`
+ * for each property. The iteratee is invoked with three arguments:
+ * (value, key, object). Iteratee functions may exit iteration early by
+ * explicitly returning `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.forOwn(new Foo, function(value, key) {
+ * console.log(key);
+ * });
+ * // => logs 'a' then 'b' (iteration order is not guaranteed)
+ */
+ function forOwn(object, iteratee) {
+ return object && baseForOwn(object, toFunction(iteratee));
}
- function unmemoize(fn) {
- return function () {
- return (fn.unmemoized || fn).apply(null, arguments);
- };
- }
+ /**
+ * Gets the index at which the first occurrence of `NaN` is found in `array`.
+ *
+ * @private
+ * @param {Array} array The array to search.
+ * @param {number} fromIndex The index to search from.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {number} Returns the index of the matched `NaN`, else `-1`.
+ */
+ function indexOfNaN(array, fromIndex, fromRight) {
+ var length = array.length,
+ index = fromIndex + (fromRight ? 0 : -1);
- function transform(arr, memo, iterator, callback) {
- if (arguments.length === 3) {
- callback = iterator;
- iterator = memo;
- memo = isArray(arr) ? [] : {};
+ while ((fromRight ? index-- : ++index < length)) {
+ var other = array[index];
+ if (other !== other) {
+ return index;
}
-
- eachOf(arr, function (v, k, cb) {
- iterator(memo, v, k, cb);
- }, function (err) {
- callback(err, memo);
- });
- }
-
- function _asyncMap(eachfn, arr, iterator, callback) {
- callback = once(callback || noop);
- arr = arr || [];
- var results = isArrayLike(arr) ? [] : {};
- eachfn(arr, function (value, index, callback) {
- iterator(value, function (err, v) {
- results[index] = v;
- callback(err);
- });
- }, function (err) {
- callback(err, results);
- });
+ }
+ return -1;
}
- var mapSeries = doSeries(_asyncMap);
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeCeil = Math.ceil;
- var nativeMax$2 = Math.max;
/**
- * The base implementation of `_.range` and `_.rangeRight` which doesn't
- * coerce arguments to numbers.
+ * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
- * @param {number} start The start of the range.
- * @param {number} end The end of the range.
- * @param {number} step The value to increment or decrement by.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Array} Returns the new array of numbers.
+ * @param {Array} array The array to search.
+ * @param {*} value The value to search for.
+ * @param {number} fromIndex The index to search from.
+ * @returns {number} Returns the index of the matched value, else `-1`.
*/
- function baseRange(start, end, step, fromRight) {
- var index = -1,
- length = nativeMax$2(nativeCeil((end - start) / (step || 1)), 0),
- result = Array(length);
-
- while (length--) {
- result[fromRight ? length : ++index] = start;
- start += step;
+ function baseIndexOf(array, value, fromIndex) {
+ if (value !== value) {
+ return indexOfNaN(array, fromIndex);
}
- return result;
- }
+ var index = fromIndex - 1,
+ length = array.length;
- function timesSeries (count, iterator, callback) {
- mapSeries(baseRange(0, count, 1), iterator, callback);
+ while (++index < length) {
+ if (array[index] === value) {
+ return index;
+ }
+ }
+ return -1;
}
- var mapLimit = doParallelLimit(_asyncMap);
+ /* Built-in method references for those with the same name as other `lodash` methods. */
+ var nativeMax$1 = Math.max;
- function timeLimit(count, limit, iterator, cb) {
- return mapLimit(baseRange(0, count, 1), limit, iterator, cb);
+ /**
+ * Gets the index at which the first occurrence of `value` is found in `array`
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons. If `fromIndex` is negative, it's used as the offset
+ * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
+ * performs a faster binary search.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to search.
+ * @param {*} value The value to search for.
+ * @param {number} [fromIndex=0] The index to search from.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ * @example
+ *
+ * _.indexOf([1, 2, 1, 2], 2);
+ * // => 1
+ *
+ * // using `fromIndex`
+ * _.indexOf([1, 2, 1, 2], 2, 2);
+ * // => 3
+ */
+ function indexOf(array, value, fromIndex) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return -1;
+ }
+ fromIndex = toInteger(fromIndex);
+ if (fromIndex < 0) {
+ fromIndex = nativeMax$1(length + fromIndex, 0);
+ }
+ return baseIndexOf(array, value, fromIndex);
}
- var map = doParallel(_asyncMap);
+ function auto (tasks, concurrency, callback) {
+ if (typeof arguments[1] === 'function') {
+ // concurrency is optional, shift the args.
+ callback = concurrency;
+ concurrency = null;
+ }
+ callback = once(callback || noop);
+ var keys$$ = keys(tasks);
+ var remainingTasks = keys$$.length;
+ if (!remainingTasks) {
+ return callback(null);
+ }
+ if (!concurrency) {
+ concurrency = remainingTasks;
+ }
- function times (count, iterator, callback) {
- map(baseRange(0, count, 1), iterator, callback);
- }
+ var results = {};
+ var runningTasks = 0;
- function sortBy(arr, iterator, cb) {
- map(arr, function (x, cb) {
- iterator(x, function (err, criteria) {
- if (err) return cb(err);
- cb(null, { value: x, criteria: criteria });
+ var listeners = [];
+ function addListener(fn) {
+ listeners.unshift(fn);
+ }
+ function removeListener(fn) {
+ var idx = indexOf(listeners, fn);
+ if (idx >= 0) listeners.splice(idx, 1);
+ }
+ function taskComplete() {
+ remainingTasks--;
+ arrayEach(listeners.slice(), function (fn) {
+ fn();
});
- }, function (err, results) {
- if (err) return cb(err);
- cb(null, arrayMap(results.sort(comparator), baseProperty('value')));
- });
-
- function comparator(left, right) {
- var a = left.criteria,
- b = right.criteria;
- return a < b ? -1 : a > b ? 1 : 0;
}
- }
- var someLimit = _createTester(eachOfLimit, Boolean, identity);
-
- function _parallel(eachfn, tasks, callback) {
- callback = callback || noop;
- var results = isArrayLike(tasks) ? [] : {};
+ addListener(function () {
+ if (!remainingTasks) {
+ callback(null, results);
+ }
+ });
- eachfn(tasks, function (task, key, callback) {
- task(rest(function (err, args) {
+ arrayEach(keys$$, function (k) {
+ var task = isArray(tasks[k]) ? tasks[k] : [tasks[k]];
+ var taskCallback = rest(function (err, args) {
+ runningTasks--;
if (args.length <= 1) {
args = args[0];
}
- results[key] = args;
- callback(err);
- }));
- }, function (err) {
- callback(err, results);
- });
- }
-
- function series(tasks, cb) {
- return _parallel(eachOfSeries, tasks, cb);
- }
-
- function seq() /* functions... */{
- var fns = arguments;
- return rest(function (args) {
- var that = this;
-
- var cb = args[args.length - 1];
- if (typeof cb == 'function') {
- args.pop();
- } else {
- cb = noop;
- }
-
- reduce(fns, args, function (newargs, fn, cb) {
- fn.apply(that, newargs.concat([rest(function (err, nextargs) {
- cb(err, nextargs);
- })]));
- }, function (err, results) {
- cb.apply(that, [err].concat(results));
+ if (err) {
+ var safeResults = {};
+ forOwn(results, function (val, rkey) {
+ safeResults[rkey] = val;
+ });
+ safeResults[k] = args;
+ callback(err, safeResults);
+ } else {
+ results[k] = args;
+ setImmediate$1(taskComplete);
+ }
});
- });
- }
-
- function retry(times, task, callback) {
- var DEFAULT_TIMES = 5;
- var DEFAULT_INTERVAL = 0;
-
- var attempts = [];
-
- var opts = {
- times: DEFAULT_TIMES,
- interval: DEFAULT_INTERVAL
- };
-
- function parseTimes(acc, t) {
- if (typeof t === 'number') {
- acc.times = parseInt(t, 10) || DEFAULT_TIMES;
- } else if (typeof t === 'object') {
- acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
- acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
- } else {
- throw new Error('Unsupported argument type for \'times\': ' + typeof t);
+ var requires = task.slice(0, task.length - 1);
+ // prevent dead-locks
+ var len = requires.length;
+ var dep;
+ while (len--) {
+ if (!(dep = tasks[requires[len]])) {
+ throw new Error('Has inexistant dependency');
+ }
+ if (isArray(dep) && indexOf(dep, k) >= 0) {
+ throw new Error('Has cyclic dependencies');
+ }
}
- }
-
- var length = arguments.length;
- if (length < 1 || length > 3) {
- throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
- } else if (length <= 2 && typeof times === 'function') {
- callback = task;
- task = times;
- }
- if (typeof times !== 'function') {
- parseTimes(opts, times);
- }
- opts.callback = callback;
- opts.task = task;
-
- function wrappedTask(wrappedCallback, wrappedResults) {
- function retryAttempt(task, finalAttempt) {
- return function (seriesCallback) {
- task(function (err, result) {
- seriesCallback(!err || finalAttempt, {
- err: err,
- result: result
- });
- }, wrappedResults);
- };
+ function ready() {
+ return runningTasks < concurrency && !baseHas(results, k) && arrayEvery(requires, function (x) {
+ return baseHas(results, x);
+ });
}
-
- function retryInterval(interval) {
- return function (seriesCallback) {
- setTimeout(function () {
- seriesCallback(null);
- }, interval);
- };
+ if (ready()) {
+ runningTasks++;
+ task[task.length - 1](taskCallback, results);
+ } else {
+ addListener(listener);
}
-
- while (opts.times) {
-
- var finalAttempt = !(opts.times -= 1);
- attempts.push(retryAttempt(opts.task, finalAttempt));
- if (!finalAttempt && opts.interval > 0) {
- attempts.push(retryInterval(opts.interval));
+ function listener() {
+ if (ready()) {
+ runningTasks++;
+ removeListener(listener);
+ task[task.length - 1](taskCallback, results);
}
}
-
- series(attempts, function (done, data) {
- data = data[data.length - 1];
- (wrappedCallback || opts.callback)(data.err, data.result);
- });
- }
-
- // If a callback is passed, run this as a controll flow
- return opts.callback ? wrappedTask() : wrappedTask;
- }
-
- function reject$1(eachfn, arr, iterator, callback) {
- _filter(eachfn, arr, function (value, cb) {
- iterator(value, function (v) {
- cb(!v);
- });
- }, callback);
+ });
}
- var rejectSeries = doSeries(reject$1);
-
- var rejectLimit = doParallelLimit(reject$1);
-
- var reject = doParallel(reject$1);
-
/**
- * A specialized version of `_.forEach` for arrays without support for
- * iteratee shorthands.
+ * A specialized version of `_.map` for arrays without support for iteratee
+ * shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns `array`.
+ * @returns {Array} Returns the new mapped array.
*/
- function arrayEach(array, iteratee) {
+ function arrayMap(array, iteratee) {
var index = -1,
- length = array.length;
+ length = array.length,
+ result = Array(length);
while (++index < length) {
- if (iteratee(array[index], index, array) === false) {
- break;
- }
+ result[index] = iteratee(array[index], index, array);
}
- return array;
+ return result;
}
function queue$1(worker, concurrency, payload) {
@@ -1488,115 +1345,164 @@
return q;
}
- function queue (worker, concurrency) {
- return queue$1(function (items, cb) {
- worker(items[0], cb);
- }, concurrency, 1);
+ function cargo(worker, payload) {
+ return queue$1(worker, 1, payload);
}
- function priorityQueue (worker, concurrency) {
- function _compareTasks(a, b) {
- return a.priority - b.priority;
- }
+ function reduce(arr, memo, iterator, cb) {
+ eachOfSeries(arr, function (x, i, cb) {
+ iterator(memo, x, function (err, v) {
+ memo = v;
+ cb(err);
+ });
+ }, function (err) {
+ cb(err, memo);
+ });
+ }
- function _binarySearch(sequence, item, compare) {
- var beg = -1,
- end = sequence.length - 1;
- while (beg < end) {
- var mid = beg + (end - beg + 1 >>> 1);
- if (compare(item, sequence[mid]) >= 0) {
- beg = mid;
- } else {
- end = mid - 1;
- }
- }
- return beg;
- }
+ function seq() /* functions... */{
+ var fns = arguments;
+ return rest(function (args) {
+ var that = this;
- function _insert(q, data, priority, callback) {
- if (callback != null && typeof callback !== 'function') {
- throw new Error('task callback must be a function');
- }
- q.started = true;
- if (!isArray(data)) {
- data = [data];
- }
- if (data.length === 0) {
- // call drain immediately if there are no tasks
- return setImmediate$1(function () {
- q.drain();
- });
+ var cb = args[args.length - 1];
+ if (typeof cb == 'function') {
+ args.pop();
+ } else {
+ cb = noop;
}
- arrayEach(data, function (task) {
- var item = {
- data: task,
- priority: priority,
- callback: typeof callback === 'function' ? callback : noop
- };
-
- q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
- if (q.tasks.length === q.concurrency) {
- q.saturated();
- }
- setImmediate$1(q.process);
+ reduce(fns, args, function (newargs, fn, cb) {
+ fn.apply(that, newargs.concat([rest(function (err, nextargs) {
+ cb(err, nextargs);
+ })]));
+ }, function (err, results) {
+ cb.apply(that, [err].concat(results));
});
- }
-
- // Start with a normal queue
- var q = queue(worker, concurrency);
+ });
+ }
- // Override push to accept second parameter representing priority
- q.push = function (data, priority, callback) {
- _insert(q, data, priority, callback);
- };
+ var reverse = Array.prototype.reverse;
- // Remove unshift function
- delete q.unshift;
+ function compose() /* functions... */{
+ return seq.apply(null, reverse.call(arguments));
+ }
- return q;
+ function concat$1(eachfn, arr, fn, callback) {
+ var result = [];
+ eachfn(arr, function (x, index, cb) {
+ fn(x, function (err, y) {
+ result = result.concat(y || []);
+ cb(err);
+ });
+ }, function (err) {
+ callback(err, result);
+ });
}
- function parallelLimit(tasks, limit, cb) {
- return _parallel(_eachOfLimit(limit), tasks, cb);
+ function doParallel(fn) {
+ return function (obj, iterator, callback) {
+ return fn(eachOf, obj, iterator, callback);
+ };
}
- function parallel(tasks, cb) {
- return _parallel(eachOf, tasks, cb);
+ var concat = doParallel(concat$1);
+
+ function doSeries(fn) {
+ return function (obj, iterator, callback) {
+ return fn(eachOfSeries, obj, iterator, callback);
+ };
}
- var nexTick = typeof process === 'object' && typeof process.nextTick === 'function' ? process.nextTick : setImmediate$1;
+ var concatSeries = doSeries(concat$1);
- function memoize(fn, hasher) {
- var memo = {};
- var queues = {};
- hasher = hasher || identity;
- var memoized = rest(function memoized(args) {
- var callback = args.pop();
- var key = hasher.apply(null, args);
- if (key in memo) {
- setImmediate$1(function () {
- callback.apply(null, memo[key]);
+ var constant = rest(function (values) {
+ var args = [null].concat(values);
+ return function (cb) {
+ return cb.apply(this, args);
+ };
+ });
+
+ function _createTester(eachfn, check, getResult) {
+ return function (arr, limit, iterator, cb) {
+ function done() {
+ if (cb) cb(getResult(false, void 0));
+ }
+ function iteratee(x, _, callback) {
+ if (!cb) return callback();
+ iterator(x, function (v) {
+ if (cb && check(v)) {
+ cb(getResult(true, x));
+ cb = iterator = false;
+ }
+ callback();
});
- } else if (key in queues) {
- queues[key].push(callback);
+ }
+ if (arguments.length > 3) {
+ eachfn(arr, limit, iteratee, done);
} else {
- queues[key] = [callback];
- fn.apply(null, args.concat([rest(function (args) {
- memo[key] = args;
- var q = queues[key];
- delete queues[key];
- for (var i = 0, l = q.length; i < l; i++) {
- q[i].apply(null, args);
- }
- })]));
+ cb = iterator;
+ iterator = limit;
+ eachfn(arr, iteratee, done);
}
- });
- memoized.memo = memo;
- memoized.unmemoized = fn;
- return memoized;
+ };
}
+ function _findGetResult(v, x) {
+ return x;
+ }
+
+ var detect = _createTester(eachOf, identity, _findGetResult);
+
+ function _eachOfLimit(limit) {
+ return function (obj, iterator, callback) {
+ callback = once(callback || noop);
+ obj = obj || [];
+ var nextKey = keyIterator(obj);
+ if (limit <= 0) {
+ return callback(null);
+ }
+ var done = false;
+ var running = 0;
+ var errored = false;
+
+ (function replenish() {
+ if (done && running <= 0) {
+ return callback(null);
+ }
+
+ while (running < limit && !errored) {
+ var key = nextKey();
+ if (key === null) {
+ done = true;
+ if (running <= 0) {
+ callback(null);
+ }
+ return;
+ }
+ running += 1;
+ iterator(obj[key], key, onlyOnce(function (err) {
+ running -= 1;
+ if (err) {
+ callback(err);
+ errored = true;
+ } else {
+ replenish();
+ }
+ }));
+ }
+ })();
+ };
+ }
+
+ function eachOfLimit(obj, limit, iterator, cb) {
+ _eachOfLimit(limit)(obj, iterator, cb);
+ }
+
+ var detectLimit = _createTester(eachOfLimit, identity, _findGetResult);
+
+ var detectSeries = _createTester(eachOfSeries, identity, _findGetResult);
+
function consoleFunc(name) {
return rest(function (fn, args) {
fn.apply(null, args.concat([rest(function (err, args) {
@@ -1615,20 +1521,7 @@
});
}
- var log = consoleFunc('log');
-
- function forever(fn, cb) {
- var done = onlyOnce(cb || noop);
- var task = ensureAsync(fn);
-
- function next(err) {
- if (err) return done(err);
- task(next);
- }
- next();
- }
-
- var everyLimit = _createTester(eachOfLimit, notId, notId);
+ var dir = consoleFunc('dir');
function during(test, iterator, cb) {
cb = cb || noop;
@@ -1651,6 +1544,26 @@
test(check);
}
+ function doDuring(iterator, test, cb) {
+ var calls = 0;
+
+ during(function (next) {
+ if (calls++ < 1) return next(null, true);
+ test.apply(this, arguments);
+ }, iterator, cb);
+ }
+
+ function whilst(test, iterator, cb) {
+ cb = cb || noop;
+ if (!test()) return cb(null);
+ var next = rest(function (err, args) {
+ if (err) return cb(err);
+ if (test.apply(this, args)) return iterator(next);
+ cb.apply(null, [null].concat(args));
+ });
+ iterator(next);
+ }
+
function doWhilst(iterator, test, cb) {
var calls = 0;
return whilst(function () {
@@ -1664,374 +1577,461 @@
}, cb);
}
- function doDuring(iterator, test, cb) {
- var calls = 0;
+ function _withoutIndex(iterator) {
+ return function (value, index, callback) {
+ return iterator(value, callback);
+ };
+ }
- during(function (next) {
- if (calls++ < 1) return next(null, true);
- test.apply(this, arguments);
- }, iterator, cb);
+ function each(arr, iterator, cb) {
+ return eachOf(arr, _withoutIndex(iterator), cb);
}
- var dir = consoleFunc('dir');
+ function eachLimit(arr, limit, iterator, cb) {
+ return _eachOfLimit(limit)(arr, _withoutIndex(iterator), cb);
+ }
- function _findGetResult(v, x) {
- return x;
+ function eachSeries(arr, iterator, cb) {
+ return eachOfSeries(arr, _withoutIndex(iterator), cb);
}
- var detectSeries = _createTester(eachOfSeries, identity, _findGetResult);
+ function ensureAsync(fn) {
+ return rest(function (args) {
+ var callback = args.pop();
+ var sync = true;
+ args.push(function () {
+ var innerArgs = arguments;
+ if (sync) {
+ setImmediate$1(function () {
+ callback.apply(null, innerArgs);
+ });
+ } else {
+ callback.apply(null, innerArgs);
+ }
+ });
+ fn.apply(this, args);
+ sync = false;
+ });
+ }
- var detectLimit = _createTester(eachOfLimit, identity, _findGetResult);
+ function notId(v) {
+ return !v;
+ }
- var detect = _createTester(eachOf, identity, _findGetResult);
+ var every = _createTester(eachOf, notId, notId);
- var constant = rest(function (values) {
- var args = [null].concat(values);
- return function (cb) {
- return cb.apply(this, args);
- };
- });
+ var everyLimit = _createTester(eachOfLimit, notId, notId);
- function concat$1(eachfn, arr, fn, callback) {
- var result = [];
- eachfn(arr, function (x, index, cb) {
- fn(x, function (err, y) {
- result = result.concat(y || []);
- cb(err);
+ function _filter(eachfn, arr, iterator, callback) {
+ var results = [];
+ eachfn(arr, function (x, index, callback) {
+ iterator(x, function (v) {
+ if (v) {
+ results.push({ index: index, value: x });
+ }
+ callback();
});
- }, function (err) {
- callback(err, result);
+ }, function () {
+ callback(arrayMap(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), baseProperty('value')));
});
}
- var concatSeries = doSeries(concat$1);
+ var filter = doParallel(_filter);
- var concat = doParallel(concat$1);
+ function doParallelLimit(fn) {
+ return function (obj, limit, iterator, callback) {
+ return fn(_eachOfLimit(limit), obj, iterator, callback);
+ };
+ }
- var reverse = Array.prototype.reverse;
+ var filterLimit = doParallelLimit(_filter);
- function compose() /* functions... */{
- return seq.apply(null, reverse.call(arguments));
+ var filterSeries = doSeries(_filter);
+
+ function forever(fn, cb) {
+ var done = onlyOnce(cb || noop);
+ var task = ensureAsync(fn);
+
+ function next(err) {
+ if (err) return done(err);
+ task(next);
+ }
+ next();
}
- function cargo(worker, payload) {
- return queue$1(worker, 1, payload);
+ function iterator (tasks) {
+ function makeCallback(index) {
+ function fn() {
+ if (tasks.length) {
+ tasks[index].apply(null, arguments);
+ }
+ return fn.next();
+ }
+ fn.next = function () {
+ return index < tasks.length - 1 ? makeCallback(index + 1) : null;
+ };
+ return fn;
+ }
+ return makeCallback(0);
}
- /**
- * A specialized version of `_.every` for arrays without support for
- * iteratee shorthands.
- *
- * @private
- * @param {Array} array The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if all elements pass the predicate check, else `false`.
- */
- function arrayEvery(array, predicate) {
- var index = -1,
- length = array.length;
+ var log = consoleFunc('log');
- while (++index < length) {
- if (!predicate(array[index], index, array)) {
- return false;
- }
- }
- return true;
+ function _asyncMap(eachfn, arr, iterator, callback) {
+ callback = once(callback || noop);
+ arr = arr || [];
+ var results = isArrayLike(arr) ? [] : {};
+ eachfn(arr, function (value, index, callback) {
+ iterator(value, function (err, v) {
+ results[index] = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
}
- /**
- * Creates a base function for methods like `_.forIn`.
- *
- * @private
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
- function createBaseFor(fromRight) {
- return function(object, iteratee, keysFunc) {
- var index = -1,
- iterable = Object(object),
- props = keysFunc(object),
- length = props.length;
+ var map = doParallel(_asyncMap);
- while (length--) {
- var key = props[fromRight ? length : ++index];
- if (iteratee(iterable[key], key, iterable) === false) {
- break;
- }
- }
- return object;
- };
+ var mapLimit = doParallelLimit(_asyncMap);
+
+ var mapSeries = doSeries(_asyncMap);
+
+ function memoize(fn, hasher) {
+ var memo = {};
+ var queues = {};
+ hasher = hasher || identity;
+ var memoized = rest(function memoized(args) {
+ var callback = args.pop();
+ var key = hasher.apply(null, args);
+ if (key in memo) {
+ setImmediate$1(function () {
+ callback.apply(null, memo[key]);
+ });
+ } else if (key in queues) {
+ queues[key].push(callback);
+ } else {
+ queues[key] = [callback];
+ fn.apply(null, args.concat([rest(function (args) {
+ memo[key] = args;
+ var q = queues[key];
+ delete queues[key];
+ for (var i = 0, l = q.length; i < l; i++) {
+ q[i].apply(null, args);
+ }
+ })]));
+ }
+ });
+ memoized.memo = memo;
+ memoized.unmemoized = fn;
+ return memoized;
}
- /**
- * The base implementation of `baseForIn` and `baseForOwn` which iterates
- * over `object` properties returned by `keysFunc` invoking `iteratee` for
- * each property. Iteratee functions may exit iteration early by explicitly
- * returning `false`.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @returns {Object} Returns `object`.
- */
- var baseFor = createBaseFor();
+ var nexTick = typeof process === 'object' && typeof process.nextTick === 'function' ? process.nextTick : setImmediate$1;
- /**
- * The base implementation of `_.forOwn` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Object} Returns `object`.
- */
- function baseForOwn(object, iteratee) {
- return object && baseFor(object, iteratee, keys);
+ function _parallel(eachfn, tasks, callback) {
+ callback = callback || noop;
+ var results = isArrayLike(tasks) ? [] : {};
+
+ eachfn(tasks, function (task, key, callback) {
+ task(rest(function (err, args) {
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[key] = args;
+ callback(err);
+ }));
+ }, function (err) {
+ callback(err, results);
+ });
}
- /**
- * Converts `value` to a function if it's not one.
- *
- * @private
- * @param {*} value The value to process.
- * @returns {Function} Returns the function.
- */
- function toFunction(value) {
- return typeof value == 'function' ? value : identity;
+ function parallel(tasks, cb) {
+ return _parallel(eachOf, tasks, cb);
}
- /**
- * Iterates over own enumerable properties of an object invoking `iteratee`
- * for each property. The iteratee is invoked with three arguments:
- * (value, key, object). Iteratee functions may exit iteration early by
- * explicitly returning `false`.
- *
- * @static
- * @memberOf _
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Object} Returns `object`.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.forOwn(new Foo, function(value, key) {
- * console.log(key);
- * });
- * // => logs 'a' then 'b' (iteration order is not guaranteed)
- */
- function forOwn(object, iteratee) {
- return object && baseForOwn(object, toFunction(iteratee));
+ function parallelLimit(tasks, limit, cb) {
+ return _parallel(_eachOfLimit(limit), tasks, cb);
}
- /**
- * Gets the index at which the first occurrence of `NaN` is found in `array`.
- *
- * @private
- * @param {Array} array The array to search.
- * @param {number} fromIndex The index to search from.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {number} Returns the index of the matched `NaN`, else `-1`.
- */
- function indexOfNaN(array, fromIndex, fromRight) {
- var length = array.length,
- index = fromIndex + (fromRight ? 0 : -1);
+ function queue (worker, concurrency) {
+ return queue$1(function (items, cb) {
+ worker(items[0], cb);
+ }, concurrency, 1);
+ }
- while ((fromRight ? index-- : ++index < length)) {
- var other = array[index];
- if (other !== other) {
- return index;
+ function priorityQueue (worker, concurrency) {
+ function _compareTasks(a, b) {
+ return a.priority - b.priority;
}
- }
- return -1;
- }
- /**
- * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
- *
- * @private
- * @param {Array} array The array to search.
- * @param {*} value The value to search for.
- * @param {number} fromIndex The index to search from.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function baseIndexOf(array, value, fromIndex) {
- if (value !== value) {
- return indexOfNaN(array, fromIndex);
- }
- var index = fromIndex - 1,
- length = array.length;
+ function _binarySearch(sequence, item, compare) {
+ var beg = -1,
+ end = sequence.length - 1;
+ while (beg < end) {
+ var mid = beg + (end - beg + 1 >>> 1);
+ if (compare(item, sequence[mid]) >= 0) {
+ beg = mid;
+ } else {
+ end = mid - 1;
+ }
+ }
+ return beg;
+ }
- while (++index < length) {
- if (array[index] === value) {
- return index;
+ function _insert(q, data, priority, callback) {
+ if (callback != null && typeof callback !== 'function') {
+ throw new Error('task callback must be a function');
+ }
+ q.started = true;
+ if (!isArray(data)) {
+ data = [data];
+ }
+ if (data.length === 0) {
+ // call drain immediately if there are no tasks
+ return setImmediate$1(function () {
+ q.drain();
+ });
+ }
+ arrayEach(data, function (task) {
+ var item = {
+ data: task,
+ priority: priority,
+ callback: typeof callback === 'function' ? callback : noop
+ };
+
+ q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
+
+ if (q.tasks.length === q.concurrency) {
+ q.saturated();
+ }
+ setImmediate$1(q.process);
+ });
}
- }
- return -1;
+
+ // Start with a normal queue
+ var q = queue(worker, concurrency);
+
+ // Override push to accept second parameter representing priority
+ q.push = function (data, priority, callback) {
+ _insert(q, data, priority, callback);
+ };
+
+ // Remove unshift function
+ delete q.unshift;
+
+ return q;
}
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeMax$1 = Math.max;
+ var slice = Array.prototype.slice;
- /**
- * Gets the index at which the first occurrence of `value` is found in `array`
- * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
- * for equality comparisons. If `fromIndex` is negative, it's used as the offset
- * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
- * performs a faster binary search.
- *
- * @static
- * @memberOf _
- * @category Array
- * @param {Array} array The array to search.
- * @param {*} value The value to search for.
- * @param {number} [fromIndex=0] The index to search from.
- * @returns {number} Returns the index of the matched value, else `-1`.
- * @example
- *
- * _.indexOf([1, 2, 1, 2], 2);
- * // => 1
- *
- * // using `fromIndex`
- * _.indexOf([1, 2, 1, 2], 2, 2);
- * // => 3
- */
- function indexOf(array, value, fromIndex) {
- var length = array ? array.length : 0;
- if (!length) {
- return -1;
- }
- fromIndex = toInteger(fromIndex);
- if (fromIndex < 0) {
- fromIndex = nativeMax$1(length + fromIndex, 0);
- }
- return baseIndexOf(array, value, fromIndex);
+ function reduceRight(arr, memo, iterator, cb) {
+ var reversed = slice.call(arr).reverse();
+ reduce(reversed, memo, iterator, cb);
}
- function auto (tasks, concurrency, callback) {
- if (typeof arguments[1] === 'function') {
- // concurrency is optional, shift the args.
- callback = concurrency;
- concurrency = null;
- }
- callback = once(callback || noop);
- var keys$$ = keys(tasks);
- var remainingTasks = keys$$.length;
- if (!remainingTasks) {
- return callback(null);
- }
- if (!concurrency) {
- concurrency = remainingTasks;
- }
+ function reject$1(eachfn, arr, iterator, callback) {
+ _filter(eachfn, arr, function (value, cb) {
+ iterator(value, function (v) {
+ cb(!v);
+ });
+ }, callback);
+ }
- var results = {};
- var runningTasks = 0;
+ var reject = doParallel(reject$1);
- var listeners = [];
- function addListener(fn) {
- listeners.unshift(fn);
+ var rejectLimit = doParallelLimit(reject$1);
+
+ var rejectSeries = doSeries(reject$1);
+
+ function series(tasks, cb) {
+ return _parallel(eachOfSeries, tasks, cb);
+ }
+
+ function retry(times, task, callback) {
+ var DEFAULT_TIMES = 5;
+ var DEFAULT_INTERVAL = 0;
+
+ var attempts = [];
+
+ var opts = {
+ times: DEFAULT_TIMES,
+ interval: DEFAULT_INTERVAL
+ };
+
+ function parseTimes(acc, t) {
+ if (typeof t === 'number') {
+ acc.times = parseInt(t, 10) || DEFAULT_TIMES;
+ } else if (typeof t === 'object') {
+ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
+ acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
+ } else {
+ throw new Error('Unsupported argument type for \'times\': ' + typeof t);
+ }
}
- function removeListener(fn) {
- var idx = indexOf(listeners, fn);
- if (idx >= 0) listeners.splice(idx, 1);
+
+ var length = arguments.length;
+ if (length < 1 || length > 3) {
+ throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
+ } else if (length <= 2 && typeof times === 'function') {
+ callback = task;
+ task = times;
}
- function taskComplete() {
- remainingTasks--;
- arrayEach(listeners.slice(), function (fn) {
- fn();
- });
+ if (typeof times !== 'function') {
+ parseTimes(opts, times);
}
+ opts.callback = callback;
+ opts.task = task;
- addListener(function () {
- if (!remainingTasks) {
- callback(null, results);
+ function wrappedTask(wrappedCallback, wrappedResults) {
+ function retryAttempt(task, finalAttempt) {
+ return function (seriesCallback) {
+ task(function (err, result) {
+ seriesCallback(!err || finalAttempt, {
+ err: err,
+ result: result
+ });
+ }, wrappedResults);
+ };
}
- });
- arrayEach(keys$$, function (k) {
- var task = isArray(tasks[k]) ? tasks[k] : [tasks[k]];
- var taskCallback = rest(function (err, args) {
- runningTasks--;
- if (args.length <= 1) {
- args = args[0];
- }
- if (err) {
- var safeResults = {};
- forOwn(results, function (val, rkey) {
- safeResults[rkey] = val;
- });
- safeResults[k] = args;
- callback(err, safeResults);
- } else {
- results[k] = args;
- setImmediate$1(taskComplete);
- }
- });
- var requires = task.slice(0, task.length - 1);
- // prevent dead-locks
- var len = requires.length;
- var dep;
- while (len--) {
- if (!(dep = tasks[requires[len]])) {
- throw new Error('Has inexistant dependency');
- }
- if (isArray(dep) && indexOf(dep, k) >= 0) {
- throw new Error('Has cyclic dependencies');
- }
- }
- function ready() {
- return runningTasks < concurrency && !baseHas(results, k) && arrayEvery(requires, function (x) {
- return baseHas(results, x);
- });
- }
- if (ready()) {
- runningTasks++;
- task[task.length - 1](taskCallback, results);
- } else {
- addListener(listener);
+ function retryInterval(interval) {
+ return function (seriesCallback) {
+ setTimeout(function () {
+ seriesCallback(null);
+ }, interval);
+ };
}
- function listener() {
- if (ready()) {
- runningTasks++;
- removeListener(listener);
- task[task.length - 1](taskCallback, results);
+
+ while (opts.times) {
+
+ var finalAttempt = !(opts.times -= 1);
+ attempts.push(retryAttempt(opts.task, finalAttempt));
+ if (!finalAttempt && opts.interval > 0) {
+ attempts.push(retryInterval(opts.interval));
}
}
- });
+
+ series(attempts, function (done, data) {
+ data = data[data.length - 1];
+ (wrappedCallback || opts.callback)(data.err, data.result);
+ });
+ }
+
+ // If a callback is passed, run this as a controll flow
+ return opts.callback ? wrappedTask() : wrappedTask;
}
- var apply = rest(function (fn, args) {
- return rest(function (callArgs) {
- return fn.apply(null, args.concat(callArgs));
- });
- });
+ var some = _createTester(eachOf, Boolean, identity);
- function applyEach$1(eachfn) {
- return rest(function (fns, args) {
- var go = rest(function (args) {
- var that = this;
- var callback = args.pop();
- return eachfn(fns, function (fn, _, cb) {
- fn.apply(that, args.concat([cb]));
- }, callback);
+ var someLimit = _createTester(eachOfLimit, Boolean, identity);
+
+ function sortBy(arr, iterator, cb) {
+ map(arr, function (x, cb) {
+ iterator(x, function (err, criteria) {
+ if (err) return cb(err);
+ cb(null, { value: x, criteria: criteria });
});
- if (args.length) {
- return go.apply(this, args);
- } else {
- return go;
- }
+ }, function (err, results) {
+ if (err) return cb(err);
+ cb(null, arrayMap(results.sort(comparator), baseProperty('value')));
});
+
+ function comparator(left, right) {
+ var a = left.criteria,
+ b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ }
}
- var applyEachSeries = applyEach$1(eachOfSeries);
+ /* Built-in method references for those with the same name as other `lodash` methods. */
+ var nativeCeil = Math.ceil;
+ var nativeMax$2 = Math.max;
+ /**
+ * The base implementation of `_.range` and `_.rangeRight` which doesn't
+ * coerce arguments to numbers.
+ *
+ * @private
+ * @param {number} start The start of the range.
+ * @param {number} end The end of the range.
+ * @param {number} step The value to increment or decrement by.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Array} Returns the new array of numbers.
+ */
+ function baseRange(start, end, step, fromRight) {
+ var index = -1,
+ length = nativeMax$2(nativeCeil((end - start) / (step || 1)), 0),
+ result = Array(length);
- var applyEach = applyEach$1(eachOf);
+ while (length--) {
+ result[fromRight ? length : ++index] = start;
+ start += step;
+ }
+ return result;
+ }
+
+ function times (count, iterator, callback) {
+ map(baseRange(0, count, 1), iterator, callback);
+ }
+
+ function timeLimit(count, limit, iterator, cb) {
+ return mapLimit(baseRange(0, count, 1), limit, iterator, cb);
+ }
+
+ function timesSeries (count, iterator, callback) {
+ mapSeries(baseRange(0, count, 1), iterator, callback);
+ }
+
+ function transform(arr, memo, iterator, callback) {
+ if (arguments.length === 3) {
+ callback = iterator;
+ iterator = memo;
+ memo = isArray(arr) ? [] : {};
+ }
+
+ eachOf(arr, function (v, k, cb) {
+ iterator(memo, v, k, cb);
+ }, function (err) {
+ callback(err, memo);
+ });
+ }
+
+ function unmemoize(fn) {
+ return function () {
+ return (fn.unmemoized || fn).apply(null, arguments);
+ };
+ }
+
+ function until(test, iterator, cb) {
+ return whilst(function () {
+ return !test.apply(this, arguments);
+ }, iterator, cb);
+ }
+
+ function waterfall (tasks, cb) {
+ cb = once(cb || noop);
+ if (!isArray(tasks)) return cb(new Error('First argument to waterfall must be an array of functions'));
+ if (!tasks.length) return cb();
+
+ function wrapIterator(iterator) {
+ return rest(function (err, args) {
+ if (err) {
+ cb.apply(null, [err].concat(args));
+ } else {
+ var next = iterator.next();
+ if (next) {
+ args.push(wrapIterator(next));
+ } else {
+ args.push(cb);
+ }
+ ensureAsync(iterator).apply(null, args);
+ }
+ });
+ }
+ wrapIterator(iterator(tasks))();
+ }
var index = {
applyEach: applyEach,
diff --git a/build/async.min.js b/build/async.min.js
index 9eb8346..ff40154 100644
--- a/build/async.min.js
+++ b/build/async.min.js
@@ -1,2 +1,2 @@
-!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.async={})}(this,function(n){"use strict";function t(n){var t=typeof n;return!!n&&("object"==t||"function"==t)}function r(n,t,r){var e=r?r.length:0;switch(e){case 0:return n.call(t);case 1:return n.call(t,r[0]);case 2:return n.call(t,r[0],r[1]);case 3:return n.call(t,r[0],r[1],r[2])}return n.apply(t,r)}function e(n){var r=t(n)?Hn.call(n):"";return r==Un||r==Cn}function u(n){if(t(n)){var r=e(n.valueOf)?n.valueOf():n;n=t(r)?r+"":r}if("string"!=typeof n)return 0===n?n:+n;n=n.replace(Qn,"");var u=Wn.test(n);return u||Gn.test(n)?Jn(n.slice(2),u?2:8):Rn.test(n)?Nn:+n}function i(n){if(!n)return 0===n?n:0;if(n=u(n),n===Kn||n===-Kn){var t=0>n?-1:1;return t*Vn}var r=n%1;return n===n?r?n-r:n:0}function o(n,t){if("function"!=typeof n)throw new TypeError(Xn);return t=Yn(void 0===t?n.length-1:i(t),0),function(){for(var e=arguments,u=-1,i=Yn(e.length-t,0),o=Array(i);++u<i;)o[u]=e[t+u];switch(t){case 0:return n.call(this,o);case 1:return n.call(this,e[0],o);case 2:return n.call(this,e[0],e[1],o)}var c=Array(t+1);for(u=-1;++u<t;)c[u]=e[u];return c[t]=o,r(n,this,c)}}function c(n){return o(function(r){var e,u=r.pop();try{e=n.apply(this,r)}catch(i){return u(i)}t(e)&&"function"==typeof e.then?e.then(function(n){u(null,n)})["catch"](function(n){u(n.message?n:new Error(n))}):u(null,e)})}function a(n,t){for(var r=-1,e=n.length,u=Array(e);++r<e;)u[r]=t(n[r],r,n);return u}function f(n){return function(t){return null==t?void 0:t[n]}}function l(n,t,r,e){var u=[];n(t,function(n,t,e){r(n,function(r){r&&u.push({index:t,value:n}),e()})},function(){e(a(u.sort(function(n,t){return n.index-t.index}),f("value")))})}function s(n,t){var r;if("function"!=typeof t)throw new TypeError(Zn);return n=i(n),function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=void 0),r}}function p(n){return s(2,n)}function h(){}function y(n){return"number"==typeof n&&n>-1&&n%1==0&&nt>=n}function m(n){return null!=n&&!("function"==typeof n&&e(n))&&y(_n(n))}function v(n,t){return rt.call(n,t)||"object"==typeof n&&t in n&&null===et(n)}function d(n){return ut(Object(n))}function g(n,t){for(var r=-1,e=Array(n);++r<n;)e[r]=t(r);return e}function k(n){return!!n&&"object"==typeof n}function b(n){return k(n)&&m(n)}function w(n){return b(n)&&ct.call(n,"callee")&&(!ft.call(n,"callee")||at.call(n)==it)}function E(n){return"string"==typeof n||!lt(n)&&k(n)&&ht.call(n)==st}function S(n){var t=n?n.length:void 0;return y(t)&&(lt(n)||E(n)||w(n))?g(t,String):null}function j(n,t){return n="number"==typeof n||mt.test(n)?+n:-1,t=null==t?yt:t,n>-1&&n%1==0&&t>n}function L(n){var t=n&&n.constructor,r="function"==typeof t&&t.prototype||vt;return n===r}function O(n){var t=L(n);if(!t&&!m(n))return d(n);var r=S(n),e=!!r,u=r||[],i=u.length;for(var o in n)!v(n,o)||e&&("length"==o||j(o,i))||t&&"constructor"==o||u.push(o);return u}function x(n){var t,r=-1;if(m(n))return t=n.length,function(){return r++,t>r?r:null};var e=O(n);return t=e.length,function(){return r++,t>r?e[r]:null}}function A(n){return function(){if(null===n)throw new Error("Callback was already called.");n.apply(this,arguments),n=null}}function I(n,t,r){function e(){var o=!0;return null===i?r(null):(t(n[i],i,A(function(n){if(n)r(n);else{if(i=u(),null===i)return r(null);o?gt(e):e()}})),void(o=!1))}r=p(r||h),n=n||[];var u=x(n),i=u();e()}function T(n){return function(t,r,e){return n(I,t,r,e)}}function z(n){return function(t,r,e){e=p(e||h),t=t||[];var u=x(t);if(0>=n)return e(null);var i=!1,o=0,c=!1;!function a(){if(i&&0>=o)return e(null);for(;n>o&&!c;){var f=u();if(null===f)return i=!0,void(0>=o&&e(null));o+=1,r(t[f],f,A(function(n){o-=1,n?(e(n),c=!0):a()}))}}()}}function M(n){return function(t,r,e,u){return n(z(r),t,e,u)}}function $(n,t,r){function e(n){o--,n?r(n):null===u&&0>=o&&r(null)}r=p(r||h),n=n||[];for(var u,i=x(n),o=0;null!=(u=i());)o+=1,t(n[u],u,A(e));0===o&&r(null)}function q(n){return function(t,r,e){return n($,t,r,e)}}function B(n,t,r,e){I(n,function(n,e,u){r(t,n,function(n,r){t=r,u(n)})},function(n){e(n,t)})}function F(n,t,r,e){var u=Et.call(n).reverse();B(u,t,r,e)}function P(n,t,r,e){z(t)(n,r,e)}function U(n){return function(t,r,e){return n(t,e)}}function C(n,t,r,e){return z(t)(n,U(r),e)}function D(n,t,r){return I(n,U(t),r)}function H(n,t,r){return $(n,U(t),r)}function N(n){return n}function Q(n,t,r){return function(e,u,i,o){function c(){o&&o(r(!1,void 0))}function a(n,e,u){return o?void i(n,function(e){o&&t(e)&&(o(r(!0,n)),o=i=!1),u()}):u()}arguments.length>3?n(e,u,a,c):(o=i,i=u,n(e,a,c))}}function R(n){return!n}function W(n,t,r){if(r=r||h,!n())return r(null);var e=o(function(u,i){return u?r(u):n.apply(this,i)?t(e):void r.apply(null,[null].concat(i))});t(e)}function G(n){return o(function(t){var r=t.pop(),e=!0;t.push(function(){var n=arguments;e?gt(function(){r.apply(null,n)}):r.apply(null,n)}),n.apply(this,t),e=!1})}function J(n){function t(r){function e(){return n.length&&n[r].apply(null,arguments),e.next()}return e.next=function(){return r<n.length-1?t(r+1):null},e}return t(0)}function K(n,t){function r(n){return o(function(e,u){if(e)t.apply(null,[e].concat(u));else{var i=n.next();i?u.push(r(i)):u.push(t),G(n).apply(null,u)}})}return t=p(t||h),lt(n)?n.length?void r(J(n))():t():t(new Error("First argument to waterfall must be an array of functions"))}function V(n,t,r){return W(function(){return!n.apply(this,arguments)},t,r)}function X(n){return function(){return(n.unmemoized||n).apply(null,arguments)}}function Y(n,t,r,e){3===arguments.length&&(e=r,r=t,t=lt(n)?[]:{}),$(n,function(n,e,u){r(t,n,e,u)},function(n){e(n,t)})}function Z(n,t,r,e){e=p(e||h),t=t||[];var u=m(t)?[]:{};n(t,function(n,t,e){r(n,function(n,r){u[t]=r,e(n)})},function(n){e(n,u)})}function _(n,t,r,e){for(var u=-1,i=xt(Ot((t-n)/(r||1)),0),o=Array(i);i--;)o[e?i:++u]=n,n+=r;return o}function nn(n,t,r){Lt(_(0,n,1),t,r)}function tn(n,t,r,e){return At(_(0,n,1),t,r,e)}function rn(n,t,r){It(_(0,n,1),t,r)}function en(n,t,r){function e(n,t){var r=n.criteria,e=t.criteria;return e>r?-1:r>e?1:0}It(n,function(n,r){t(n,function(t,e){return t?r(t):void r(null,{value:n,criteria:e})})},function(n,t){return n?r(n):void r(null,a(t.sort(e),f("value")))})}function un(n,t,r){r=r||h;var e=m(t)?[]:{};n(t,function(n,t,r){n(o(function(n,u){u.length<=1&&(u=u[0]),e[t]=u,r(n)}))},function(n){r(n,e)})}function on(n,t){return un(I,n,t)}function cn(){var n=arguments;return o(function(t){var r=this,e=t[t.length-1];"function"==typeof e?t.pop():e=h,B(n,t,function(n,t,e){t.apply(r,n.concat([o(function(n,t){e(n,t)})]))},function(n,t){e.apply(r,[n].concat(t))})})}function an(n,t,r){function e(n,t){if("number"==typeof t)n.times=parseInt(t,10)||i;else{if("object"!=typeof t)throw new Error("Unsupported argument type for 'times': "+typeof t);n.times=parseInt(t.times,10)||i,n.interval=parseInt(t.interval,10)||o}}function u(n,t){function r(n,r){return function(e){n(function(n,t){e(!n||r,{err:n,result:t})},t)}}function e(n){return function(t){setTimeout(function(){t(null)},n)}}for(;a.times;){var u=!(a.times-=1);c.push(r(a.task,u)),!u&&a.interval>0&&c.push(e(a.interval))}on(c,function(t,r){r=r[r.length-1],(n||a.callback)(r.err,r.result)})}var i=5,o=0,c=[],a={times:i,interval:o},f=arguments.length;if(1>f||f>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=f&&"function"==typeof n&&(r=t,t=n),"function"!=typeof n&&e(a,n),a.callback=r,a.task=t,a.callback?u():u}function fn(n,t,r,e){l(n,t,function(n,t){r(n,function(n){t(!n)})},e)}function ln(n,t){for(var r=-1,e=n.length;++r<e&&t(n[r],r,n)!==!1;);return n}function sn(n,t,r){function e(n,t,r,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return n.started=!0,lt(t)||(t=[t]),0===t.length&&n.idle()?gt(function(){n.drain()}):(ln(t,function(t){var u={data:t,callback:e||h};r?n.tasks.unshift(u):n.tasks.push(u),n.tasks.length===n.concurrency&&n.saturated()}),void gt(n.process))}function u(n,t){return function(){i-=1;var r=!1,e=arguments;ln(t,function(n){ln(o,function(t,e){t!==n||r||(o.splice(e,1),r=!0)}),n.callback.apply(n,e)}),n.tasks.length+i===0&&n.drain(),n.process()}}if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var i=0,o=[],c={tasks:[],concurrency:t,payload:r,saturated:h,empty:h,drain:h,started:!1,paused:!1,push:function(n,t){e(c,n,!1,t)},kill:function(){c.drain=h,c.tasks=[]},unshift:function(n,t){e(c,n,!0,t)},process:function(){for(;!c.paused&&i<c.concurrency&&c.tasks.length;){var t=c.payload?c.tasks.splice(0,c.payload):c.tasks.splice(0,c.tasks.length),r=a(t,f("data"));0===c.tasks.length&&c.empty(),i+=1,o.push(t[0]);var e=A(u(c,t));n(r,e)}},length:function(){return c.tasks.length},running:function(){return i},workersList:function(){return o},idle:function(){return c.tasks.length+i===0},pause:function(){c.paused=!0},resume:function(){if(c.paused!==!1){c.paused=!1;for(var n=Math.min(c.concurrency,c.tasks.length),t=1;n>=t;t++)gt(c.process)}}};return c}function pn(n,t){return sn(function(t,r){n(t[0],r)},t,1)}function hn(n,t){function r(n,t){return n.priority-t.priority}function e(n,t,r){for(var e=-1,u=n.length-1;u>e;){var i=e+(u-e+1>>>1);r(t,n[i])>=0?e=i:u=i-1}return e}function u(n,t,u,i){if(null!=i&&"function"!=typeof i)throw new Error("task callback must be a function");return n.started=!0,lt(t)||(t=[t]),0===t.length?gt(function(){n.drain()}):void ln(t,function(t){var o={data:t,priority:u,callback:"function"==typeof i?i:h};n.tasks.splice(e(n.tasks,o,r)+1,0,o),n.tasks.length===n.concurrency&&n.saturated(),gt(n.process)})}var i=pn(n,t);return i.push=function(n,t,r){u(i,n,t,r)},delete i.unshift,i}function yn(n,t,r){return un(z(t),n,r)}function mn(n,t){return un($,n,t)}function vn(n,t){var r={},e={};t=t||N;var u=o(function(u){var i=u.pop(),c=t.apply(null,u);c in r?gt(function(){i.apply(null,r[c])}):c in e?e[c].push(i):(e[c]=[i],n.apply(null,u.concat([o(function(n){r[c]=n;var t=e[c];delete e[c];for(var u=0,i=t.length;i>u;u++)t[u].apply(null,n)})])))});return u.memo=r,u.unmemoized=n,u}function dn(n){return o(function(t,r){t.apply(null,r.concat([o(function(t,r){"object"==typeof console&&(t?console.error&&console.error(t):console[n]&&ln(r,function(t){console[n](t)}))})]))})}function gn(n,t){function r(n){return n?e(n):void u(r)}var e=A(t||h),u=G(n);r()}function kn(n,t,r){r=r||h;var e=o(function(t,e){t?r(t):(e.push(u),n.apply(this,e))}),u=function(n,u){return n?r(n):u?void t(e):r(null)};n(u)}function bn(n,t,r){var e=0;return W(function(){return++e<=1||t.apply(this,arguments)},n,r)}function wn(n,t,r){return bn(n,function(){return!t.apply(this,arguments)},r)}function En(n,t,r){var e=0;kn(function(n){return e++<1?n(null,!0):void t.apply(this,arguments)},n,r)}function Sn(n,t){return t}function jn(n,t,r,e){var u=[];n(t,function(n,t,e){r(n,function(n,t){u=u.concat(t||[]),e(n)})},function(n){e(n,u)})}function Ln(){return cn.apply(null,Rt.call(arguments))}function On(n,t){return sn(n,1,t)}function xn(n,t){for(var r=-1,e=n.length;++r<e;)if(!t(n[r],r,n))return!1;return!0}function An(n){return function(t,r,e){for(var u=-1,i=Object(t),o=e(t),c=o.length;c--;){var a=o[n?c:++u];if(r(i[a],a,i)===!1)break}return t}}function In(n,t){return n&&Wt(n,t,O)}function Tn(n){return"function"==typeof n?n:N}function zn(n,t){return n&&In(n,Tn(t))}function Mn(n,t,r){for(var e=n.length,u=t+(r?0:-1);r?u--:++u<e;){var i=n[u];if(i!==i)return u}return-1}function $n(n,t,r){if(t!==t)return Mn(n,r);for(var e=r-1,u=n.length;++e<u;)if(n[e]===t)return e;return-1}function qn(n,t,r){var e=n?n.length:0;return e?(r=i(r),0>r&&(r=Gt(e+r,0)),$n(n,t,r)):-1}function Bn(n,t,r){function e(n){s.unshift(n)}function u(n){var t=qn(s,n);t>=0&&s.splice(t,1)}function i(){a--,ln(s.slice(),function(n){n()})}"function"==typeof arguments[1]&&(r=t,t=null),r=p(r||h);var c=O(n),a=c.length;if(!a)return r(null);t||(t=a);var f={},l=0,s=[];e(function(){a||r(null,f)}),ln(c,function(c){function a(){return t>l&&!v(f,c)&&xn(m,function(n){return v(f,n)})}function s(){a()&&(l++,u(s),h[h.length-1](y,f))}for(var p,h=lt(n[c])?n[c]:[n[c]],y=o(function(n,t){if(l--,t.length<=1&&(t=t[0]),n){var e={};zn(f,function(n,t){e[t]=n}),e[c]=t,r(n,e)}else f[c]=t,gt(i)}),m=h.slice(0,h.length-1),d=m.length;d--;){if(!(p=n[m[d]]))throw new Error("Has inexistant dependency");if(lt(p)&&qn(p,c)>=0)throw new Error("Has cyclic dependencies")}a()?(l++,h[h.length-1](y,f)):e(s)})}function Fn(n){return o(function(t,r){var e=o(function(r){var e=this,u=r.pop();return n(t,function(n,t,u){n.apply(e,r.concat([u]))},u)});return r.length?e.apply(this,r):e})}var Pn,Un="[object Function]",Cn="[object GeneratorFunction]",Dn=Object.prototype,Hn=Dn.toString,Nn=NaN,Qn=/^\s+|\s+$/g,Rn=/^[-+]0x[0-9a-f]+$/i,Wn=/^0b[01]+$/i,Gn=/^0o[0-7]+$/i,Jn=parseInt,Kn=1/0,Vn=1.7976931348623157e308,Xn="Expected a function",Yn=Math.max,Zn="Expected a function",_n=f("length"),nt=9007199254740991,tt=Object.prototype,rt=tt.hasOwnProperty,et=Object.getPrototypeOf,ut=Object.keys,it="[object Arguments]",ot=Object.prototype,ct=ot.hasOwnProperty,at=ot.toString,ft=ot.propertyIsEnumerable,lt=Array.isArray,st="[object String]",pt=Object.prototype,ht=pt.toString,yt=9007199254740991,mt=/^(?:0|[1-9]\d*)$/,vt=Object.prototype,dt="function"==typeof setImmediate&&setImmediate;Pn=dt?function(n){dt(n)}:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:function(n){setTimeout(n,0)};var gt=Pn,kt=T(l),bt=M(l),wt=q(l),Et=Array.prototype.slice,St=Q($,Boolean,N),jt=Q($,R,R),Lt=T(Z),Ot=Math.ceil,xt=Math.max,At=M(Z),It=q(Z),Tt=Q(P,Boolean,N),zt=T(fn),Mt=M(fn),$t=q(fn),qt="object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:gt,Bt=dn("log"),Ft=Q(P,R,R),Pt=dn("dir"),Ut=Q(I,N,Sn),Ct=Q(P,N,Sn),Dt=Q($,N,Sn),Ht=o(function(n){var t=[null].concat(n);return function(n){return n.apply(this,t)}}),Nt=T(jn),Qt=q(jn),Rt=Array.prototype.reverse,Wt=An(),Gt=Math.max,Jt=o(function(n,t){return o(function(r){return n.apply(null,t.concat(r))})}),Kt=Fn(I),Vt=Fn($),Xt={applyEach:Vt,applyEachSeries:Kt,apply:Jt,asyncify:c,auto:Bn,cargo:On,compose:Ln,concat:Qt,concatSeries:Nt,constant:Ht,detect:Dt,detectLimit:Ct,detectSeries:Ut,dir:Pt,doDuring:En,doUntil:wn,doWhilst:bn,during:kn,each:H,eachLimit:C,eachOf:$,eachOfLimit:P,eachOfSeries:I,eachSeries:D,ensureAsync:G,every:jt,everyLimit:Ft,filter:wt,filterLimit:bt,filterSeries:kt,forever:gn,iterator:J,log:Bt,map:It,mapLimit:At,mapSeries:Lt,memoize:vn,nextTick:qt,parallel:mn,parallelLimit:yn,priorityQueue:hn,queue:pn,reduce:B,reduceRight:F,reject:$t,rejectLimit:Mt,rejectSeries:zt,retry:an,seq:cn,series:on,setImmediate:gt,some:St,someLimit:Tt,sortBy:en,times:rn,timesLimit:tn,timesSeries:nn,transform:Y,unmemoize:X,until:V,waterfall:K,whilst:W,all:jt,any:St,forEach:H,forEachSeries:D,forEachLimit:C,forEachOf:$,forEachOfSeries:I,forEachOfLimit:P,inject:B,foldl:B,foldr:F,select:wt,selectLimit:bt,selectSeries:kt,wrapSync:c};n["default"]=Xt,n.applyEach=Vt,n.applyEachSeries=Kt,n.apply=Jt,n.asyncify=c,n.auto=Bn,n.cargo=On,n.compose=Ln,n.concat=Qt,n.concatSeries=Nt,n.constant=Ht,n.detect=Dt,n.detectLimit=Ct,n.detectSeries=Ut,n.dir=Pt,n.doDuring=En,n.doUntil=wn,n.doWhilst=bn,n.during=kn,n.each=H,n.eachLimit=C,n.eachOf=$,n.eachOfLimit=P,n.eachOfSeries=I,n.eachSeries=D,n.ensureAsync=G,n.every=jt,n.everyLimit=Ft,n.filter=wt,n.filterLimit=bt,n.filterSeries=kt,n.forever=gn,n.iterator=J,n.log=Bt,n.map=It,n.mapLimit=At,n.mapSeries=Lt,n.memoize=vn,n.nextTick=qt,n.parallel=mn,n.parallelLimit=yn,n.priorityQueue=hn,n.queue=pn,n.reduce=B,n.reduceRight=F,n.reject=$t,n.rejectLimit=Mt,n.rejectSeries=zt,n.retry=an,n.seq=cn,n.series=on,n.setImmediate=gt,n.some=St,n.someLimit=Tt,n.sortBy=en,n.times=rn,n.timesLimit=tn,n.timesSeries=nn,n.transform=Y,n.unmemoize=X,n.until=V,n.waterfall=K,n.whilst=W,n.all=jt,n.any=St,n.forEach=H,n.forEachSeries=D,n.forEachLimit=C,n.forEachOf=$,n.forEachOfSeries=I,n.forEachOfLimit=P,n.inject=B,n.foldl=B,n.foldr=F,n.select=wt,n.selectLimit=bt,n.selectSeries=kt,n.wrapSync=c});
+!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.async={})}(this,function(n){"use strict";function t(n,t,r){var e=r?r.length:0;switch(e){case 0:return n.call(t);case 1:return n.call(t,r[0]);case 2:return n.call(t,r[0],r[1]);case 3:return n.call(t,r[0],r[1],r[2])}return n.apply(t,r)}function r(n){var t=typeof n;return!!n&&("object"==t||"function"==t)}function e(n){var t=r(n)?Hn.call(n):"";return t==Un||t==Cn}function u(n){if(r(n)){var t=e(n.valueOf)?n.valueOf():n;n=r(t)?t+"":t}if("string"!=typeof n)return 0===n?n:+n;n=n.replace(Qn,"");var u=Wn.test(n);return u||Gn.test(n)?Jn(n.slice(2),u?2:8):Rn.test(n)?Nn:+n}function i(n){if(!n)return 0===n?n:0;if(n=u(n),n===Kn||n===-Kn){var t=0>n?-1:1;return t*Vn}var r=n%1;return n===n?r?n-r:n:0}function o(n,r){if("function"!=typeof n)throw new TypeError(Xn);return r=Yn(void 0===r?n.length-1:i(r),0),function(){for(var e=arguments,u=-1,i=Yn(e.length-r,0),o=Array(i);++u<i;)o[u]=e[r+u];switch(r){case 0:return n.call(this,o);case 1:return n.call(this,e[0],o);case 2:return n.call(this,e[0],e[1],o)}var c=Array(r+1);for(u=-1;++u<r;)c[u]=e[u];return c[r]=o,t(n,this,c)}}function c(n){return o(function(t,r){var e=o(function(r){var e=this,u=r.pop();return n(t,function(n,t,u){n.apply(e,r.concat([u]))},u)});return r.length?e.apply(this,r):e})}function a(n,t){var r;if("function"!=typeof t)throw new TypeError(Zn);return n=i(n),function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=void 0),r}}function f(n){return a(2,n)}function l(){}function s(n){return function(t){return null==t?void 0:t[n]}}function p(n){return"number"==typeof n&&n>-1&&n%1==0&&nt>=n}function h(n){return null!=n&&!("function"==typeof n&&e(n))&&p(_n(n))}function y(n,t){return rt.call(n,t)||"object"==typeof n&&t in n&&null===et(n)}function m(n){return ut(Object(n))}function v(n,t){for(var r=-1,e=Array(n);++r<n;)e[r]=t(r);return e}function d(n){return!!n&&"object"==typeof n}function g(n){return d(n)&&h(n)}function k(n){return g(n)&&ct.call(n,"callee")&&(!ft.call(n,"callee")||at.call(n)==it)}function b(n){return"string"==typeof n||!lt(n)&&d(n)&&ht.call(n)==st}function w(n){var t=n?n.length:void 0;return p(t)&&(lt(n)||b(n)||k(n))?v(t,String):null}function E(n,t){return n="number"==typeof n||mt.test(n)?+n:-1,t=null==t?yt:t,n>-1&&n%1==0&&t>n}function S(n){var t=n&&n.constructor,r="function"==typeof t&&t.prototype||vt;return n===r}function j(n){var t=S(n);if(!t&&!h(n))return m(n);var r=w(n),e=!!r,u=r||[],i=u.length;for(var o in n)!y(n,o)||e&&("length"==o||E(o,i))||t&&"constructor"==o||u.push(o);return u}function L(n){var t,r=-1;if(h(n))return t=n.length,function(){return r++,t>r?r:null};var e=j(n);return t=e.length,function(){return r++,t>r?e[r]:null}}function O(n){return function(){if(null===n)throw new Error("Callback was already called.");n.apply(this,arguments),n=null}}function x(n,t,r){function e(n){o--,n?r(n):null===u&&0>=o&&r(null)}r=f(r||l),n=n||[];for(var u,i=L(n),o=0;null!=(u=i());)o+=1,t(n[u],u,O(e));0===o&&r(null)}function A(n,t,r){function e(){var o=!0;return null===i?r(null):(t(n[i],i,O(function(n){if(n)r(n);else{if(i=u(),null===i)return r(null);o?kt(e):e()}})),void(o=!1))}r=f(r||l),n=n||[];var u=L(n),i=u();e()}function I(n){return o(function(t){var e,u=t.pop();try{e=n.apply(this,t)}catch(i){return u(i)}r(e)&&"function"==typeof e.then?e.then(function(n){u(null,n)})["catch"](function(n){u(n.message?n:new Error(n))}):u(null,e)})}function T(n,t){for(var r=-1,e=n.length;++r<e&&t(n[r],r,n)!==!1;);return n}function z(n,t){for(var r=-1,e=n.length;++r<e;)if(!t(n[r],r,n))return!1;return!0}function M(n){return function(t,r,e){for(var u=-1,i=Object(t),o=e(t),c=o.length;c--;){var a=o[n?c:++u];if(r(i[a],a,i)===!1)break}return t}}function $(n,t){return n&&Et(n,t,j)}function q(n){return n}function B(n){return"function"==typeof n?n:q}function F(n,t){return n&&$(n,B(t))}function P(n,t,r){for(var e=n.length,u=t+(r?0:-1);r?u--:++u<e;){var i=n[u];if(i!==i)return u}return-1}function U(n,t,r){if(t!==t)return P(n,r);for(var e=r-1,u=n.length;++e<u;)if(n[e]===t)return e;return-1}function C(n,t,r){var e=n?n.length:0;return e?(r=i(r),0>r&&(r=St(e+r,0)),U(n,t,r)):-1}function D(n,t,r){function e(n){h.unshift(n)}function u(n){var t=C(h,n);t>=0&&h.splice(t,1)}function i(){a--,T(h.slice(),function(n){n()})}"function"==typeof arguments[1]&&(r=t,t=null),r=f(r||l);var c=j(n),a=c.length;if(!a)return r(null);t||(t=a);var s={},p=0,h=[];e(function(){a||r(null,s)}),T(c,function(c){function a(){return t>p&&!y(s,c)&&z(v,function(n){return y(s,n)})}function f(){a()&&(p++,u(f),h[h.length-1](m,s))}for(var l,h=lt(n[c])?n[c]:[n[c]],m=o(function(n,t){if(p--,t.length<=1&&(t=t[0]),n){var e={};F(s,function(n,t){e[t]=n}),e[c]=t,r(n,e)}else s[c]=t,kt(i)}),v=h.slice(0,h.length-1),d=v.length;d--;){if(!(l=n[v[d]]))throw new Error("Has inexistant dependency");if(lt(l)&&C(l,c)>=0)throw new Error("Has cyclic dependencies")}a()?(p++,h[h.length-1](m,s)):e(f)})}function H(n,t){for(var r=-1,e=n.length,u=Array(e);++r<e;)u[r]=t(n[r],r,n);return u}function N(n,t,r){function e(n,t,r,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return n.started=!0,lt(t)||(t=[t]),0===t.length&&n.idle()?kt(function(){n.drain()}):(T(t,function(t){var u={data:t,callback:e||l};r?n.tasks.unshift(u):n.tasks.push(u),n.tasks.length===n.concurrency&&n.saturated()}),void kt(n.process))}function u(n,t){return function(){i-=1;var r=!1,e=arguments;T(t,function(n){T(o,function(t,e){t!==n||r||(o.splice(e,1),r=!0)}),n.callback.apply(n,e)}),n.tasks.length+i===0&&n.drain(),n.process()}}if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var i=0,o=[],c={tasks:[],concurrency:t,payload:r,saturated:l,empty:l,drain:l,started:!1,paused:!1,push:function(n,t){e(c,n,!1,t)},kill:function(){c.drain=l,c.tasks=[]},unshift:function(n,t){e(c,n,!0,t)},process:function(){for(;!c.paused&&i<c.concurrency&&c.tasks.length;){var t=c.payload?c.tasks.splice(0,c.payload):c.tasks.splice(0,c.tasks.length),r=H(t,s("data"));0===c.tasks.length&&c.empty(),i+=1,o.push(t[0]);var e=O(u(c,t));n(r,e)}},length:function(){return c.tasks.length},running:function(){return i},workersList:function(){return o},idle:function(){return c.tasks.length+i===0},pause:function(){c.paused=!0},resume:function(){if(c.paused!==!1){c.paused=!1;for(var n=Math.min(c.concurrency,c.tasks.length),t=1;n>=t;t++)kt(c.process)}}};return c}function Q(n,t){return N(n,1,t)}function R(n,t,r,e){A(n,function(n,e,u){r(t,n,function(n,r){t=r,u(n)})},function(n){e(n,t)})}function W(){var n=arguments;return o(function(t){var r=this,e=t[t.length-1];"function"==typeof e?t.pop():e=l,R(n,t,function(n,t,e){t.apply(r,n.concat([o(function(n,t){e(n,t)})]))},function(n,t){e.apply(r,[n].concat(t))})})}function G(){return W.apply(null,jt.call(arguments))}function J(n,t,r,e){var u=[];n(t,function(n,t,e){r(n,function(n,t){u=u.concat(t||[]),e(n)})},function(n){e(n,u)})}function K(n){return function(t,r,e){return n(x,t,r,e)}}function V(n){return function(t,r,e){return n(A,t,r,e)}}function X(n,t,r){return function(e,u,i,o){function c(){o&&o(r(!1,void 0))}function a(n,e,u){return o?void i(n,function(e){o&&t(e)&&(o(r(!0,n)),o=i=!1),u()}):u()}arguments.length>3?n(e,u,a,c):(o=i,i=u,n(e,a,c))}}function Y(n,t){return t}function Z(n){return function(t,r,e){e=f(e||l),t=t||[];var u=L(t);if(0>=n)return e(null);var i=!1,o=0,c=!1;!function a(){if(i&&0>=o)return e(null);for(;n>o&&!c;){var f=u();if(null===f)return i=!0,void(0>=o&&e(null));o+=1,r(t[f],f,O(function(n){o-=1,n?(e(n),c=!0):a()}))}}()}}function _(n,t,r,e){Z(t)(n,r,e)}function nn(n){return o(function(t,r){t.apply(null,r.concat([o(function(t,r){"object"==typeof console&&(t?console.error&&console.error(t):console[n]&&T(r,function(t){console[n](t)}))})]))})}function tn(n,t,r){r=r||l;var e=o(function(t,e){t?r(t):(e.push(u),n.apply(this,e))}),u=function(n,u){return n?r(n):u?void t(e):r(null)};n(u)}function rn(n,t,r){var e=0;tn(function(n){return e++<1?n(null,!0):void t.apply(this,arguments)},n,r)}function en(n,t,r){if(r=r||l,!n())return r(null);var e=o(function(u,i){return u?r(u):n.apply(this,i)?t(e):void r.apply(null,[null].concat(i))});t(e)}function un(n,t,r){var e=0;return en(function(){return++e<=1||t.apply(this,arguments)},n,r)}function on(n,t,r){return un(n,function(){return!t.apply(this,arguments)},r)}function cn(n){return function(t,r,e){return n(t,e)}}function an(n,t,r){return x(n,cn(t),r)}function fn(n,t,r,e){return Z(t)(n,cn(r),e)}function ln(n,t,r){return A(n,cn(t),r)}function sn(n){return o(function(t){var r=t.pop(),e=!0;t.push(function(){var n=arguments;e?kt(function(){r.apply(null,n)}):r.apply(null,n)}),n.apply(this,t),e=!1})}function pn(n){return!n}function hn(n,t,r,e){var u=[];n(t,function(n,t,e){r(n,function(r){r&&u.push({index:t,value:n}),e()})},function(){e(H(u.sort(function(n,t){return n.index-t.index}),s("value")))})}function yn(n){return function(t,r,e,u){return n(Z(r),t,e,u)}}function mn(n,t){function r(n){return n?e(n):void u(r)}var e=O(t||l),u=sn(n);r()}function vn(n){function t(r){function e(){return n.length&&n[r].apply(null,arguments),e.next()}return e.next=function(){return r<n.length-1?t(r+1):null},e}return t(0)}function dn(n,t,r,e){e=f(e||l),t=t||[];var u=h(t)?[]:{};n(t,function(n,t,e){r(n,function(n,r){u[t]=r,e(n)})},function(n){e(n,u)})}function gn(n,t){var r={},e={};t=t||q;var u=o(function(u){var i=u.pop(),c=t.apply(null,u);c in r?kt(function(){i.apply(null,r[c])}):c in e?e[c].push(i):(e[c]=[i],n.apply(null,u.concat([o(function(n){r[c]=n;var t=e[c];delete e[c];for(var u=0,i=t.length;i>u;u++)t[u].apply(null,n)})])))});return u.memo=r,u.unmemoized=n,u}function kn(n,t,r){r=r||l;var e=h(t)?[]:{};n(t,function(n,t,r){n(o(function(n,u){u.length<=1&&(u=u[0]),e[t]=u,r(n)}))},function(n){r(n,e)})}function bn(n,t){return kn(x,n,t)}function wn(n,t,r){return kn(Z(t),n,r)}function En(n,t){return N(function(t,r){n(t[0],r)},t,1)}function Sn(n,t){function r(n,t){return n.priority-t.priority}function e(n,t,r){for(var e=-1,u=n.length-1;u>e;){var i=e+(u-e+1>>>1);r(t,n[i])>=0?e=i:u=i-1}return e}function u(n,t,u,i){if(null!=i&&"function"!=typeof i)throw new Error("task callback must be a function");return n.started=!0,lt(t)||(t=[t]),0===t.length?kt(function(){n.drain()}):void T(t,function(t){var o={data:t,priority:u,callback:"function"==typeof i?i:l};n.tasks.splice(e(n.tasks,o,r)+1,0,o),n.tasks.length===n.concurrency&&n.saturated(),kt(n.process)})}var i=En(n,t);return i.push=function(n,t,r){u(i,n,t,r)},delete i.unshift,i}function jn(n,t,r,e){var u=Nt.call(n).reverse();R(u,t,r,e)}function Ln(n,t,r,e){hn(n,t,function(n,t){r(n,function(n){t(!n)})},e)}function On(n,t){return kn(A,n,t)}function xn(n,t,r){function e(n,t){if("number"==typeof t)n.times=parseInt(t,10)||i;else{if("object"!=typeof t)throw new Error("Unsupported argument type for 'times': "+typeof t);n.times=parseInt(t.times,10)||i,n.interval=parseInt(t.interval,10)||o}}function u(n,t){function r(n,r){return function(e){n(function(n,t){e(!n||r,{err:n,result:t})},t)}}function e(n){return function(t){setTimeout(function(){t(null)},n)}}for(;a.times;){var u=!(a.times-=1);c.push(r(a.task,u)),!u&&a.interval>0&&c.push(e(a.interval))}On(c,function(t,r){r=r[r.length-1],(n||a.callback)(r.err,r.result)})}var i=5,o=0,c=[],a={times:i,interval:o},f=arguments.length;if(1>f||f>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=f&&"function"==typeof n&&(r=t,t=n),"function"!=typeof n&&e(a,n),a.callback=r,a.task=t,a.callback?u():u}function An(n,t,r){function e(n,t){var r=n.criteria,e=t.criteria;return e>r?-1:r>e?1:0}Ut(n,function(n,r){t(n,function(t,e){return t?r(t):void r(null,{value:n,criteria:e})})},function(n,t){return n?r(n):void r(null,H(t.sort(e),s("value")))})}function In(n,t,r,e){for(var u=-1,i=Vt(Kt((t-n)/(r||1)),0),o=Array(i);i--;)o[e?i:++u]=n,n+=r;return o}function Tn(n,t,r){Ut(In(0,n,1),t,r)}function zn(n,t,r,e){return Ct(In(0,n,1),t,r,e)}function Mn(n,t,r){Dt(In(0,n,1),t,r)}function $n(n,t,r,e){3===arguments.length&&(e=r,r=t,t=lt(n)?[]:{}),x(n,function(n,e,u){r(t,n,e,u)},function(n){e(n,t)})}function qn(n){return function(){return(n.unmemoized||n).apply(null,arguments)}}function Bn(n,t,r){return en(function(){return!n.apply(this,arguments)},t,r)}function Fn(n,t){function r(n){return o(function(e,u){if(e)t.apply(null,[e].concat(u));else{var i=n.next();i?u.push(r(i)):u.push(t),sn(n).apply(null,u)}})}return t=f(t||l),lt(n)?n.length?void r(vn(n))():t():t(new Error("First argument to waterfall must be an array of functions"))}var Pn,Un="[object Function]",Cn="[object GeneratorFunction]",Dn=Object.prototype,Hn=Dn.toString,Nn=NaN,Qn=/^\s+|\s+$/g,Rn=/^[-+]0x[0-9a-f]+$/i,Wn=/^0b[01]+$/i,Gn=/^0o[0-7]+$/i,Jn=parseInt,Kn=1/0,Vn=1.7976931348623157e308,Xn="Expected a function",Yn=Math.max,Zn="Expected a function",_n=s("length"),nt=9007199254740991,tt=Object.prototype,rt=tt.hasOwnProperty,et=Object.getPrototypeOf,ut=Object.keys,it="[object Arguments]",ot=Object.prototype,ct=ot.hasOwnProperty,at=ot.toString,ft=ot.propertyIsEnumerable,lt=Array.isArray,st="[object String]",pt=Object.prototype,ht=pt.toString,yt=9007199254740991,mt=/^(?:0|[1-9]\d*)$/,vt=Object.prototype,dt=c(x),gt="function"==typeof setImmediate&&setImmediate;Pn=gt?function(n){gt(n)}:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:function(n){setTimeout(n,0)};var kt=Pn,bt=c(A),wt=o(function(n,t){return o(function(r){return n.apply(null,t.concat(r))})}),Et=M(),St=Math.max,jt=Array.prototype.reverse,Lt=K(J),Ot=V(J),xt=o(function(n){var t=[null].concat(n);return function(n){return n.apply(this,t)}}),At=X(x,q,Y),It=X(_,q,Y),Tt=X(A,q,Y),zt=nn("dir"),Mt=X(x,pn,pn),$t=X(_,pn,pn),qt=K(hn),Bt=yn(hn),Ft=V(hn),Pt=nn("log"),Ut=K(dn),Ct=yn(dn),Dt=V(dn),Ht="object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:kt,Nt=Array.prototype.slice,Qt=K(Ln),Rt=yn(Ln),Wt=V(Ln),Gt=X(x,Boolean,q),Jt=X(_,Boolean,q),Kt=Math.ceil,Vt=Math.max,Xt={applyEach:dt,applyEachSeries:bt,apply:wt,asyncify:I,auto:D,cargo:Q,compose:G,concat:Lt,concatSeries:Ot,constant:xt,detect:At,detectLimit:It,detectSeries:Tt,dir:zt,doDuring:rn,doUntil:on,doWhilst:un,during:tn,each:an,eachLimit:fn,eachOf:x,eachOfLimit:_,eachOfSeries:A,eachSeries:ln,ensureAsync:sn,every:Mt,everyLimit:$t,filter:qt,filterLimit:Bt,filterSeries:Ft,forever:mn,iterator:vn,log:Pt,map:Ut,mapLimit:Ct,mapSeries:Dt,memoize:gn,nextTick:Ht,parallel:bn,parallelLimit:wn,priorityQueue:Sn,queue:En,reduce:R,reduceRight:jn,reject:Qt,rejectLimit:Rt,rejectSeries:Wt,retry:xn,seq:W,series:On,setImmediate:kt,some:Gt,someLimit:Jt,sortBy:An,times:Tn,timesLimit:zn,timesSeries:Mn,transform:$n,unmemoize:qn,until:Bn,waterfall:Fn,whilst:en,all:Mt,any:Gt,forEach:an,forEachSeries:ln,forEachLimit:fn,forEachOf:x,forEachOfSeries:A,forEachOfLimit:_,inject:R,foldl:R,foldr:jn,select:qt,selectLimit:Bt,selectSeries:Ft,wrapSync:I};n["default"]=Xt,n.applyEach=dt,n.applyEachSeries=bt,n.apply=wt,n.asyncify=I,n.auto=D,n.cargo=Q,n.compose=G,n.concat=Lt,n.concatSeries=Ot,n.constant=xt,n.detect=At,n.detectLimit=It,n.detectSeries=Tt,n.dir=zt,n.doDuring=rn,n.doUntil=on,n.doWhilst=un,n.during=tn,n.each=an,n.eachLimit=fn,n.eachOf=x,n.eachOfLimit=_,n.eachOfSeries=A,n.eachSeries=ln,n.ensureAsync=sn,n.every=Mt,n.everyLimit=$t,n.filter=qt,n.filterLimit=Bt,n.filterSeries=Ft,n.forever=mn,n.iterator=vn,n.log=Pt,n.map=Ut,n.mapLimit=Ct,n.mapSeries=Dt,n.memoize=gn,n.nextTick=Ht,n.parallel=bn,n.parallelLimit=wn,n.priorityQueue=Sn,n.queue=En,n.reduce=R,n.reduceRight=jn,n.reject=Qt,n.rejectLimit=Rt,n.rejectSeries=Wt,n.retry=xn,n.seq=W,n.series=On,n.setImmediate=kt,n.some=Gt,n.someLimit=Jt,n.sortBy=An,n.times=Tn,n.timesLimit=zn,n.timesSeries=Mn,n.transform=$n,n.unmemoize=qn,n.until=Bn,n.waterfall=Fn,n.whilst=en,n.all=Mt,n.any=Gt,n.forEach=an,n.forEachSeries=ln,n.forEachLimit=fn,n.forEachOf=x,n.forEachOfSeries=A,n.forEachOfLimit=_,n.inject=R,n.foldl=R,n.foldr=jn,n.select=qt,n.selectLimit=Bt,n.selectSeries=Ft,n.wrapSync=I});
//# sourceMappingURL=dist/async.min.map \ No newline at end of file
diff --git a/build/bower.json b/build/bower.json
new file mode 100644
index 0000000..b2a4f3c
--- /dev/null
+++ b/build/bower.json
@@ -0,0 +1,68 @@
+{
+ "name": "async",
+ "description": "Higher-order functions and common patterns for asynchronous code",
+ "main": "index.js",
+ "keywords": [
+ "async",
+ "callback",
+ "module",
+ "utility"
+ ],
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/caolan/async.git"
+ },
+ "devDependencies": {
+ "babel-cli": "^6.3.17",
+ "babel-core": "^6.3.26",
+ "babel-plugin-add-module-exports": "~0.1.2",
+ "babel-plugin-transform-es2015-modules-commonjs": "^6.3.16",
+ "babel-preset-es2015": "^6.3.13",
+ "babelify": "^7.2.0",
+ "benchmark": "bestiejs/benchmark.js",
+ "bluebird": "^2.9.32",
+ "chai": "^3.1.0",
+ "coveralls": "^2.11.2",
+ "es6-promise": "^2.3.0",
+ "fs-extra": "^0.26.3",
+ "gulp": "~3.9.0",
+ "jscs": "^1.13.1",
+ "jshint": "~2.8.0",
+ "karma": "^0.13.2",
+ "karma-browserify": "^4.2.1",
+ "karma-firefox-launcher": "^0.1.6",
+ "karma-mocha": "^0.2.0",
+ "karma-mocha-reporter": "^1.0.2",
+ "mocha": "^2.2.5",
+ "native-promise-only": "^0.8.0-a",
+ "nodeunit": ">0.0.0",
+ "nyc": "^2.1.0",
+ "recursive-readdir": "^1.3.0",
+ "rimraf": "^2.5.0",
+ "rollup": "^0.25.0",
+ "rollup-plugin-npm": "~1.3.0",
+ "rsvp": "^3.0.18",
+ "semver": "^4.3.6",
+ "uglify-js": "~2.4.0",
+ "vinyl-buffer": "~1.0.0",
+ "vinyl-source-stream": "~1.1.0",
+ "xyz": "^0.5.0",
+ "yargs": "~3.9.1"
+ },
+ "moduleType": [
+ "amd",
+ "globals",
+ "node"
+ ],
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "test",
+ "tests"
+ ],
+ "authors": [
+ "Caolan McMahon"
+ ]
+} \ No newline at end of file
diff --git a/build/component.json b/build/component.json
new file mode 100644
index 0000000..b699237
--- /dev/null
+++ b/build/component.json
@@ -0,0 +1,17 @@
+{
+ "name": "async",
+ "description": "Higher-order functions and common patterns for asynchronous code",
+ "version": "2.0.0-alpha",
+ "keywords": [
+ "async",
+ "callback",
+ "module",
+ "utility"
+ ],
+ "license": "MIT",
+ "main": "index.js",
+ "repository": "caolan/async",
+ "scripts": [
+ "index.js"
+ ]
+} \ No newline at end of file
diff --git a/build/es/apply.js b/build/es/apply.js
new file mode 100644
index 0000000..eeceb43
--- /dev/null
+++ b/build/es/apply.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import rest from 'lodash-es/rest';
+
+export default rest(function(fn, args) {
+ return rest(function(callArgs) {
+ return fn.apply(null, args.concat(callArgs));
+ });
+});
diff --git a/build/es/applyEach.js b/build/es/applyEach.js
new file mode 100644
index 0000000..2c5f001
--- /dev/null
+++ b/build/es/applyEach.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import applyEach from './internal/applyEach';
+import eachOf from './eachOf';
+
+export default applyEach(eachOf);
diff --git a/build/es/applyEachSeries.js b/build/es/applyEachSeries.js
new file mode 100644
index 0000000..e917618
--- /dev/null
+++ b/build/es/applyEachSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import applyEach from './internal/applyEach';
+import eachOfSeries from './eachOfSeries';
+
+export default applyEach(eachOfSeries);
diff --git a/build/es/asyncify.js b/build/es/asyncify.js
new file mode 100644
index 0000000..9239e99
--- /dev/null
+++ b/build/es/asyncify.js
@@ -0,0 +1,26 @@
+'use strict';
+
+import isObject from 'lodash-es/isObject';
+import rest from 'lodash-es/rest';
+
+export default function asyncify(func) {
+ return rest(function (args) {
+ var callback = args.pop();
+ var result;
+ try {
+ result = func.apply(this, args);
+ } catch (e) {
+ return callback(e);
+ }
+ // if result is Promise object
+ if (isObject(result) && typeof result.then === 'function') {
+ result.then(function(value) {
+ callback(null, value);
+ })['catch'](function(err) {
+ callback(err.message ? err : new Error(err));
+ });
+ } else {
+ callback(null, result);
+ }
+ });
+}
diff --git a/build/es/auto.js b/build/es/auto.js
new file mode 100644
index 0000000..19f4215
--- /dev/null
+++ b/build/es/auto.js
@@ -0,0 +1,109 @@
+'use strict';
+
+import arrayEach from 'lodash-es/internal/arrayEach';
+import arrayEvery from 'lodash-es/internal/arrayEvery';
+import baseHas from 'lodash-es/internal/baseHas';
+import forOwn from 'lodash-es/forOwn';
+import indexOf from 'lodash-es/indexOf';
+import isArray from 'lodash-es/isArray';
+import okeys from 'lodash-es/keys';
+import noop from 'lodash-es/noop';
+import once from 'lodash-es/once';
+import rest from 'lodash-es/rest';
+
+import setImmediate from './internal/setImmediate';
+
+export default function (tasks, concurrency, callback) {
+ if (typeof arguments[1] === 'function') {
+ // concurrency is optional, shift the args.
+ callback = concurrency;
+ concurrency = null;
+ }
+ callback = once(callback || noop);
+ var keys = okeys(tasks);
+ var remainingTasks = keys.length;
+ if (!remainingTasks) {
+ return callback(null);
+ }
+ if (!concurrency) {
+ concurrency = remainingTasks;
+ }
+
+ var results = {};
+ var runningTasks = 0;
+
+ var listeners = [];
+ function addListener(fn) {
+ listeners.unshift(fn);
+ }
+ function removeListener(fn) {
+ var idx = indexOf(listeners, fn);
+ if (idx >= 0) listeners.splice(idx, 1);
+ }
+ function taskComplete() {
+ remainingTasks--;
+ arrayEach(listeners.slice(), function (fn) {
+ fn();
+ });
+ }
+
+ addListener(function () {
+ if (!remainingTasks) {
+ callback(null, results);
+ }
+ });
+
+ arrayEach(keys, function (k) {
+ var task = isArray(tasks[k]) ? tasks[k]: [tasks[k]];
+ var taskCallback = rest(function(err, args) {
+ runningTasks--;
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ if (err) {
+ var safeResults = {};
+ forOwn(results, function(val, rkey) {
+ safeResults[rkey] = val;
+ });
+ safeResults[k] = args;
+ callback(err, safeResults);
+ }
+ else {
+ results[k] = args;
+ setImmediate(taskComplete);
+ }
+ });
+ var requires = task.slice(0, task.length - 1);
+ // prevent dead-locks
+ var len = requires.length;
+ var dep;
+ while (len--) {
+ if (!(dep = tasks[requires[len]])) {
+ throw new Error('Has inexistant dependency');
+ }
+ if (isArray(dep) && indexOf(dep, k) >= 0) {
+ throw new Error('Has cyclic dependencies');
+ }
+ }
+ function ready() {
+ return runningTasks < concurrency && !baseHas(results, k) &&
+ arrayEvery(requires, function (x) {
+ return baseHas(results, x);
+ });
+ }
+ if (ready()) {
+ runningTasks++;
+ task[task.length - 1](taskCallback, results);
+ }
+ else {
+ addListener(listener);
+ }
+ function listener() {
+ if (ready()) {
+ runningTasks++;
+ removeListener(listener);
+ task[task.length - 1](taskCallback, results);
+ }
+ }
+ });
+}
diff --git a/build/es/cargo.js b/build/es/cargo.js
new file mode 100644
index 0000000..b90ab0f
--- /dev/null
+++ b/build/es/cargo.js
@@ -0,0 +1,7 @@
+'use strict';
+
+import queue from './internal/queue';
+
+export default function cargo(worker, payload) {
+ return queue(worker, 1, payload);
+}
diff --git a/build/es/compose.js b/build/es/compose.js
new file mode 100644
index 0000000..9e92521
--- /dev/null
+++ b/build/es/compose.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import seq from './seq';
+
+var reverse = Array.prototype.reverse;
+
+export default function compose(/* functions... */) {
+ return seq.apply(null, reverse.call(arguments));
+}
diff --git a/build/es/concat.js b/build/es/concat.js
new file mode 100644
index 0000000..af019a3
--- /dev/null
+++ b/build/es/concat.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import concat from './internal/concat';
+import doParallel from './internal/doParallel';
+
+export default doParallel(concat);
diff --git a/build/es/concatSeries.js b/build/es/concatSeries.js
new file mode 100644
index 0000000..76f4043
--- /dev/null
+++ b/build/es/concatSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import concat from './internal/concat';
+import doSeries from './internal/doSeries';
+
+export default doSeries(concat);
diff --git a/build/es/constant.js b/build/es/constant.js
new file mode 100644
index 0000000..492d11b
--- /dev/null
+++ b/build/es/constant.js
@@ -0,0 +1,10 @@
+'use strict';
+
+import rest from 'lodash-es/rest';
+
+export default rest(function(values) {
+ var args = [null].concat(values);
+ return function (cb) {
+ return cb.apply(this, args);
+ };
+});
diff --git a/build/es/detect.js b/build/es/detect.js
new file mode 100644
index 0000000..19fffef
--- /dev/null
+++ b/build/es/detect.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import identity from 'lodash-es/identity';
+
+import createTester from './internal/createTester';
+import eachOf from './eachOf';
+import findGetResult from './internal/findGetResult';
+
+export default createTester(eachOf, identity, findGetResult);
diff --git a/build/es/detectLimit.js b/build/es/detectLimit.js
new file mode 100644
index 0000000..0fc46db
--- /dev/null
+++ b/build/es/detectLimit.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import identity from 'lodash-es/identity';
+
+import createTester from './internal/createTester';
+import eachOfLimit from './eachOfLimit';
+import findGetResult from './internal/findGetResult';
+
+export default createTester(eachOfLimit, identity, findGetResult);
diff --git a/build/es/detectSeries.js b/build/es/detectSeries.js
new file mode 100644
index 0000000..26f48ba
--- /dev/null
+++ b/build/es/detectSeries.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import identity from 'lodash-es/identity';
+
+import createTester from './internal/createTester';
+import eachOfSeries from './eachOfSeries';
+import findGetResult from './internal/findGetResult';
+
+export default createTester(eachOfSeries, identity, findGetResult);
diff --git a/build/es/dir.js b/build/es/dir.js
new file mode 100644
index 0000000..049b416
--- /dev/null
+++ b/build/es/dir.js
@@ -0,0 +1,5 @@
+'use strict';
+
+import consoleFunc from './internal/consoleFunc';
+
+export default consoleFunc('dir');
diff --git a/build/es/doDuring.js b/build/es/doDuring.js
new file mode 100644
index 0000000..c13e62b
--- /dev/null
+++ b/build/es/doDuring.js
@@ -0,0 +1,12 @@
+'use strict';
+
+import during from './during';
+
+export default function doDuring(iterator, test, cb) {
+ var calls = 0;
+
+ during(function(next) {
+ if (calls++ < 1) return next(null, true);
+ test.apply(this, arguments);
+ }, iterator, cb);
+}
diff --git a/build/es/doUntil.js b/build/es/doUntil.js
new file mode 100644
index 0000000..3bc783f
--- /dev/null
+++ b/build/es/doUntil.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import doWhilst from './doWhilst';
+
+export default function doUntil(iterator, test, cb) {
+ return doWhilst(iterator, function() {
+ return !test.apply(this, arguments);
+ }, cb);
+}
diff --git a/build/es/doWhilst.js b/build/es/doWhilst.js
new file mode 100644
index 0000000..b05d1d8
--- /dev/null
+++ b/build/es/doWhilst.js
@@ -0,0 +1,10 @@
+'use strict';
+
+import whilst from './whilst';
+
+export default function doWhilst(iterator, test, cb) {
+ var calls = 0;
+ return whilst(function() {
+ return ++calls <= 1 || test.apply(this, arguments);
+ }, iterator, cb);
+}
diff --git a/build/es/during.js b/build/es/during.js
new file mode 100644
index 0000000..e9809cd
--- /dev/null
+++ b/build/es/during.js
@@ -0,0 +1,25 @@
+'use strict';
+
+import noop from 'lodash-es/noop';
+import rest from 'lodash-es/rest';
+
+export default function during(test, iterator, cb) {
+ cb = cb || noop;
+
+ var next = rest(function(err, args) {
+ if (err) {
+ cb(err);
+ } else {
+ args.push(check);
+ test.apply(this, args);
+ }
+ });
+
+ var check = function(err, truth) {
+ if (err) return cb(err);
+ if (!truth) return cb(null);
+ iterator(next);
+ };
+
+ test(check);
+}
diff --git a/build/es/each.js b/build/es/each.js
new file mode 100644
index 0000000..384bb0a
--- /dev/null
+++ b/build/es/each.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import eachOf from './eachOf';
+import withoutIndex from './internal/withoutIndex';
+
+export default function each(arr, iterator, cb) {
+ return eachOf(arr, withoutIndex(iterator), cb);
+}
diff --git a/build/es/eachLimit.js b/build/es/eachLimit.js
new file mode 100644
index 0000000..5009cc3
--- /dev/null
+++ b/build/es/eachLimit.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import eachOfLimit from './internal/eachOfLimit';
+import withoutIndex from './internal/withoutIndex';
+
+
+export default function eachLimit(arr, limit, iterator, cb) {
+ return eachOfLimit(limit)(arr, withoutIndex(iterator), cb);
+}
diff --git a/build/es/eachOf.js b/build/es/eachOf.js
new file mode 100644
index 0000000..e06f2bb
--- /dev/null
+++ b/build/es/eachOf.js
@@ -0,0 +1,34 @@
+'use strict';
+
+import once from 'lodash-es/once';
+import noop from 'lodash-es/noop';
+
+import keyIterator from './internal/keyIterator';
+import onlyOnce from './internal/onlyOnce';
+
+export default function eachOf(object, iterator, callback) {
+ callback = once(callback || noop);
+ object = object || [];
+
+ var iter = keyIterator(object);
+ var key, completed = 0;
+
+ while ((key = iter()) != null) {
+ completed += 1;
+ iterator(object[key], key, onlyOnce(done));
+ }
+
+ if (completed === 0) callback(null);
+
+ function done(err) {
+ completed--;
+ if (err) {
+ callback(err);
+ }
+ // Check key is null in case iterator isn't exhausted
+ // and done resolved synchronously.
+ else if (key === null && completed <= 0) {
+ callback(null);
+ }
+ }
+}
diff --git a/build/es/eachOfLimit.js b/build/es/eachOfLimit.js
new file mode 100644
index 0000000..e381474
--- /dev/null
+++ b/build/es/eachOfLimit.js
@@ -0,0 +1,7 @@
+'use strict';
+
+import _eachOfLimit from './internal/eachOfLimit';
+
+export default function eachOfLimit(obj, limit, iterator, cb) {
+ _eachOfLimit(limit)(obj, iterator, cb);
+}
diff --git a/build/es/eachOfSeries.js b/build/es/eachOfSeries.js
new file mode 100644
index 0000000..2456bbb
--- /dev/null
+++ b/build/es/eachOfSeries.js
@@ -0,0 +1,40 @@
+'use strict';
+
+import once from 'lodash-es/once';
+import noop from 'lodash-es/noop';
+
+import keyIterator from './internal/keyIterator';
+import onlyOnce from './internal/onlyOnce';
+import setImmediate from './setImmediate';
+
+export default function eachOfSeries(obj, iterator, callback) {
+ callback = once(callback || noop);
+ obj = obj || [];
+ var nextKey = keyIterator(obj);
+ var key = nextKey();
+
+ function iterate() {
+ var sync = true;
+ if (key === null) {
+ return callback(null);
+ }
+ iterator(obj[key], key, onlyOnce(function(err) {
+ if (err) {
+ callback(err);
+ } else {
+ key = nextKey();
+ if (key === null) {
+ return callback(null);
+ } else {
+ if (sync) {
+ setImmediate(iterate);
+ } else {
+ iterate();
+ }
+ }
+ }
+ }));
+ sync = false;
+ }
+ iterate();
+}
diff --git a/build/es/eachSeries.js b/build/es/eachSeries.js
new file mode 100644
index 0000000..fd08c04
--- /dev/null
+++ b/build/es/eachSeries.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import eachOfSeries from './eachOfSeries';
+import withoutIndex from './internal/withoutIndex';
+
+export default function eachSeries(arr, iterator, cb) {
+ return eachOfSeries(arr, withoutIndex(iterator), cb);
+}
diff --git a/build/es/ensureAsync.js b/build/es/ensureAsync.js
new file mode 100644
index 0000000..ba9affd
--- /dev/null
+++ b/build/es/ensureAsync.js
@@ -0,0 +1,24 @@
+'use strict';
+
+import rest from 'lodash-es/rest';
+
+import setImmediate from './internal/setImmediate';
+
+export default function ensureAsync(fn) {
+ return rest(function (args) {
+ var callback = args.pop();
+ var sync = true;
+ args.push(function () {
+ var innerArgs = arguments;
+ if (sync) {
+ setImmediate(function () {
+ callback.apply(null, innerArgs);
+ });
+ } else {
+ callback.apply(null, innerArgs);
+ }
+ });
+ fn.apply(this, args);
+ sync = false;
+ });
+}
diff --git a/build/es/every.js b/build/es/every.js
new file mode 100644
index 0000000..7ee3713
--- /dev/null
+++ b/build/es/every.js
@@ -0,0 +1,7 @@
+'use strict';
+
+import createTester from './internal/createTester';
+import eachOf from './eachOf';
+import notId from './internal/notId';
+
+export default createTester(eachOf, notId, notId);
diff --git a/build/es/everyLimit.js b/build/es/everyLimit.js
new file mode 100644
index 0000000..4b3fc5f
--- /dev/null
+++ b/build/es/everyLimit.js
@@ -0,0 +1,7 @@
+'use strict';
+
+import createTester from './internal/createTester';
+import eachOfLimit from './eachOfLimit';
+import notId from './internal/notId';
+
+export default createTester(eachOfLimit, notId, notId);
diff --git a/build/es/filter.js b/build/es/filter.js
new file mode 100644
index 0000000..36af2b1
--- /dev/null
+++ b/build/es/filter.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import filter from './internal/filter';
+import doParallel from './internal/doParallel';
+
+export default doParallel(filter);
diff --git a/build/es/filterLimit.js b/build/es/filterLimit.js
new file mode 100644
index 0000000..8fe237f
--- /dev/null
+++ b/build/es/filterLimit.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import filter from './internal/filter';
+import doParallelLimit from './internal/doParallelLimit';
+
+export default doParallelLimit(filter);
diff --git a/build/es/filterSeries.js b/build/es/filterSeries.js
new file mode 100644
index 0000000..861ca8b
--- /dev/null
+++ b/build/es/filterSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import filter from './internal/filter';
+import doSeries from './internal/doSeries';
+
+export default doSeries(filter);
diff --git a/build/es/forever.js b/build/es/forever.js
new file mode 100644
index 0000000..fca0684
--- /dev/null
+++ b/build/es/forever.js
@@ -0,0 +1,17 @@
+'use strict';
+
+import noop from 'lodash-es/noop';
+
+import onlyOnce from './internal/onlyOnce';
+import ensureAsync from './ensureAsync';
+
+export default function forever(fn, cb) {
+ var done = onlyOnce(cb || noop);
+ var task = ensureAsync(fn);
+
+ function next(err) {
+ if (err) return done(err);
+ task(next);
+ }
+ next();
+}
diff --git a/build/es/index.js b/build/es/index.js
new file mode 100644
index 0000000..a165909
--- /dev/null
+++ b/build/es/index.js
@@ -0,0 +1,228 @@
+'use strict';
+
+import applyEach from './applyEach';
+import applyEachSeries from './applyEachSeries';
+import apply from './apply';
+import asyncify from './asyncify';
+import auto from './auto';
+import cargo from './cargo';
+import compose from './compose';
+import concat from './concat';
+import concatSeries from './concatSeries';
+import constant from './constant';
+import detect from './detect';
+import detectLimit from './detectLimit';
+import detectSeries from './detectSeries';
+import dir from './dir';
+import doDuring from './doDuring';
+import doUntil from './doUntil';
+import doWhilst from './doWhilst';
+import during from './during';
+import each from './each';
+import eachLimit from './eachLimit';
+import eachOf from './eachOf';
+import eachOfLimit from './eachOfLimit';
+import eachOfSeries from './eachOfSeries';
+import eachSeries from './eachSeries';
+import ensureAsync from './ensureAsync';
+import every from './every';
+import everyLimit from './everyLimit';
+import filter from './filter';
+import filterLimit from './filterLimit';
+import filterSeries from './filterSeries';
+import forever from './forever';
+import iterator from './iterator';
+import log from './log';
+import map from './map';
+import mapLimit from './mapLimit';
+import mapSeries from './mapSeries';
+import memoize from './memoize';
+import nextTick from './nextTick';
+import parallel from './parallel';
+import parallelLimit from './parallelLimit';
+import priorityQueue from './priorityQueue';
+import queue from './queue';
+import reduce from './reduce';
+import reduceRight from './reduceRight';
+import reject from './reject';
+import rejectLimit from './rejectLimit';
+import rejectSeries from './rejectSeries';
+import retry from './retry';
+import seq from './seq';
+import series from './series';
+import setImmediate from './setImmediate';
+import some from './some';
+import someLimit from './someLimit';
+import sortBy from './sortBy';
+import times from './times';
+import timesLimit from './timesLimit';
+import timesSeries from './timesSeries';
+import transform from './transform';
+import unmemoize from './unmemoize';
+import until from './until';
+import waterfall from './waterfall';
+import whilst from './whilst';
+
+export default {
+ applyEach: applyEach,
+ applyEachSeries: applyEachSeries,
+ apply: apply,
+ asyncify: asyncify,
+ auto: auto,
+ cargo: cargo,
+ compose: compose,
+ concat: concat,
+ concatSeries: concatSeries,
+ constant: constant,
+ detect: detect,
+ detectLimit: detectLimit,
+ detectSeries: detectSeries,
+ dir: dir,
+ doDuring: doDuring,
+ doUntil: doUntil,
+ doWhilst: doWhilst,
+ during: during,
+ each: each,
+ eachLimit: eachLimit,
+ eachOf: eachOf,
+ eachOfLimit: eachOfLimit,
+ eachOfSeries: eachOfSeries,
+ eachSeries: eachSeries,
+ ensureAsync: ensureAsync,
+ every: every,
+ everyLimit: everyLimit,
+ filter: filter,
+ filterLimit: filterLimit,
+ filterSeries: filterSeries,
+ forever: forever,
+ iterator: iterator,
+ log: log,
+ map: map,
+ mapLimit: mapLimit,
+ mapSeries: mapSeries,
+ memoize: memoize,
+ nextTick: nextTick,
+ parallel: parallel,
+ parallelLimit: parallelLimit,
+ priorityQueue: priorityQueue,
+ queue: queue,
+ reduce: reduce,
+ reduceRight: reduceRight,
+ reject: reject,
+ rejectLimit: rejectLimit,
+ rejectSeries: rejectSeries,
+ retry: retry,
+ seq: seq,
+ series: series,
+ setImmediate: setImmediate,
+ some: some,
+ someLimit: someLimit,
+ sortBy: sortBy,
+ times: times,
+ timesLimit: timesLimit,
+ timesSeries: timesSeries,
+ transform: transform,
+ unmemoize: unmemoize,
+ until: until,
+ waterfall: waterfall,
+ whilst: whilst,
+
+ // aliases
+ all: every,
+ any: some,
+ forEach: each,
+ forEachSeries: eachSeries,
+ forEachLimit: eachLimit,
+ forEachOf: eachOf,
+ forEachOfSeries: eachOfSeries,
+ forEachOfLimit: eachOfLimit,
+ inject: reduce,
+ foldl: reduce,
+ foldr: reduceRight,
+ select: filter,
+ selectLimit: filterLimit,
+ selectSeries: filterSeries,
+ wrapSync: asyncify
+};
+
+export {
+ applyEach as applyEach,
+ applyEachSeries as applyEachSeries,
+ apply as apply,
+ asyncify as asyncify,
+ auto as auto,
+ cargo as cargo,
+ compose as compose,
+ concat as concat,
+ concatSeries as concatSeries,
+ constant as constant,
+ detect as detect,
+ detectLimit as detectLimit,
+ detectSeries as detectSeries,
+ dir as dir,
+ doDuring as doDuring,
+ doUntil as doUntil,
+ doWhilst as doWhilst,
+ during as during,
+ each as each,
+ eachLimit as eachLimit,
+ eachOf as eachOf,
+ eachOfLimit as eachOfLimit,
+ eachOfSeries as eachOfSeries,
+ eachSeries as eachSeries,
+ ensureAsync as ensureAsync,
+ every as every,
+ everyLimit as everyLimit,
+ filter as filter,
+ filterLimit as filterLimit,
+ filterSeries as filterSeries,
+ forever as forever,
+ iterator as iterator,
+ log as log,
+ map as map,
+ mapLimit as mapLimit,
+ mapSeries as mapSeries,
+ memoize as memoize,
+ nextTick as nextTick,
+ parallel as parallel,
+ parallelLimit as parallelLimit,
+ priorityQueue as priorityQueue,
+ queue as queue,
+ reduce as reduce,
+ reduceRight as reduceRight,
+ reject as reject,
+ rejectLimit as rejectLimit,
+ rejectSeries as rejectSeries,
+ retry as retry,
+ seq as seq,
+ series as series,
+ setImmediate as setImmediate,
+ some as some,
+ someLimit as someLimit,
+ sortBy as sortBy,
+ times as times,
+ timesLimit as timesLimit,
+ timesSeries as timesSeries,
+ transform as transform,
+ unmemoize as unmemoize,
+ until as until,
+ waterfall as waterfall,
+ whilst as whilst,
+
+ // Aliases
+ every as all,
+ some as any,
+ each as forEach,
+ eachSeries as forEachSeries,
+ eachLimit as forEachLimit,
+ eachOf as forEachOf,
+ eachOfSeries as forEachOfSeries,
+ eachOfLimit as forEachOfLimit,
+ reduce as inject,
+ reduce as foldl,
+ reduceRight as foldr,
+ filter as select,
+ filterLimit as selectLimit,
+ filterSeries as selectSeries,
+ asyncify as wrapSync
+};
diff --git a/build/es/internal/applyEach.js b/build/es/internal/applyEach.js
new file mode 100644
index 0000000..1467363
--- /dev/null
+++ b/build/es/internal/applyEach.js
@@ -0,0 +1,22 @@
+'use strict';
+
+import rest from 'lodash-es/rest';
+
+export default function applyEach(eachfn) {
+ return rest(function(fns, args) {
+ var go = rest(function(args) {
+ var that = this;
+ var callback = args.pop();
+ return eachfn(fns, function (fn, _, cb) {
+ fn.apply(that, args.concat([cb]));
+ },
+ callback);
+ });
+ if (args.length) {
+ return go.apply(this, args);
+ }
+ else {
+ return go;
+ }
+ });
+}
diff --git a/build/es/internal/concat.js b/build/es/internal/concat.js
new file mode 100644
index 0000000..482ad3a
--- /dev/null
+++ b/build/es/internal/concat.js
@@ -0,0 +1,13 @@
+'use strict';
+
+export default function concat(eachfn, arr, fn, callback) {
+ var result = [];
+ eachfn(arr, function (x, index, cb) {
+ fn(x, function (err, y) {
+ result = result.concat(y || []);
+ cb(err);
+ });
+ }, function (err) {
+ callback(err, result);
+ });
+}
diff --git a/build/es/internal/consoleFunc.js b/build/es/internal/consoleFunc.js
new file mode 100644
index 0000000..7796d87
--- /dev/null
+++ b/build/es/internal/consoleFunc.js
@@ -0,0 +1,23 @@
+'use strict';
+
+import arrayEach from 'lodash-es/internal/arrayEach';
+import rest from 'lodash-es/rest';
+
+export default function consoleFunc(name) {
+ return rest(function (fn, args) {
+ fn.apply(null, args.concat([rest(function (err, args) {
+ if (typeof console === 'object') {
+ if (err) {
+ if (console.error) {
+ console.error(err);
+ }
+ }
+ else if (console[name]) {
+ arrayEach(args, function (x) {
+ console[name](x);
+ });
+ }
+ }
+ })]));
+ });
+}
diff --git a/build/es/internal/createTester.js b/build/es/internal/createTester.js
new file mode 100644
index 0000000..1bf2e89
--- /dev/null
+++ b/build/es/internal/createTester.js
@@ -0,0 +1,26 @@
+'use strict';
+
+export default function _createTester(eachfn, check, getResult) {
+ return function(arr, limit, iterator, cb) {
+ function done() {
+ if (cb) cb(getResult(false, void 0));
+ }
+ function iteratee(x, _, callback) {
+ if (!cb) return callback();
+ iterator(x, function (v) {
+ if (cb && check(v)) {
+ cb(getResult(true, x));
+ cb = iterator = false;
+ }
+ callback();
+ });
+ }
+ if (arguments.length > 3) {
+ eachfn(arr, limit, iteratee, done);
+ } else {
+ cb = iterator;
+ iterator = limit;
+ eachfn(arr, iteratee, done);
+ }
+ };
+}
diff --git a/build/es/internal/doParallel.js b/build/es/internal/doParallel.js
new file mode 100644
index 0000000..19c90fc
--- /dev/null
+++ b/build/es/internal/doParallel.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import eachOf from '../eachOf';
+
+export default function doParallel(fn) {
+ return function (obj, iterator, callback) {
+ return fn(eachOf, obj, iterator, callback);
+ };
+}
diff --git a/build/es/internal/doParallelLimit.js b/build/es/internal/doParallelLimit.js
new file mode 100644
index 0000000..0c3bcf7
--- /dev/null
+++ b/build/es/internal/doParallelLimit.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import eachOfLimit from './eachOfLimit';
+
+export default function doParallelLimit(fn) {
+ return function (obj, limit, iterator, callback) {
+ return fn(eachOfLimit(limit), obj, iterator, callback);
+ };
+}
diff --git a/build/es/internal/doSeries.js b/build/es/internal/doSeries.js
new file mode 100644
index 0000000..c7f1d99
--- /dev/null
+++ b/build/es/internal/doSeries.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import eachOfSeries from '../eachOfSeries';
+
+export default function doSeries(fn) {
+ return function (obj, iterator, callback) {
+ return fn(eachOfSeries, obj, iterator, callback);
+ };
+}
diff --git a/build/es/internal/eachOfLimit.js b/build/es/internal/eachOfLimit.js
new file mode 100644
index 0000000..5235278
--- /dev/null
+++ b/build/es/internal/eachOfLimit.js
@@ -0,0 +1,49 @@
+'use strict';
+
+import noop from 'lodash-es/noop';
+import once from 'lodash-es/once';
+
+import keyIterator from './keyIterator';
+import onlyOnce from './onlyOnce';
+
+export default function _eachOfLimit(limit) {
+ return function (obj, iterator, callback) {
+ callback = once(callback || noop);
+ obj = obj || [];
+ var nextKey = keyIterator(obj);
+ if (limit <= 0) {
+ return callback(null);
+ }
+ var done = false;
+ var running = 0;
+ var errored = false;
+
+ (function replenish () {
+ if (done && running <= 0) {
+ return callback(null);
+ }
+
+ while (running < limit && !errored) {
+ var key = nextKey();
+ if (key === null) {
+ done = true;
+ if (running <= 0) {
+ callback(null);
+ }
+ return;
+ }
+ running += 1;
+ iterator(obj[key], key, onlyOnce(function (err) {
+ running -= 1;
+ if (err) {
+ callback(err);
+ errored = true;
+ }
+ else {
+ replenish();
+ }
+ }));
+ }
+ })();
+ };
+}
diff --git a/build/es/internal/filter.js b/build/es/internal/filter.js
new file mode 100644
index 0000000..f58eb52
--- /dev/null
+++ b/build/es/internal/filter.js
@@ -0,0 +1,20 @@
+'use strict';
+
+import arrayMap from 'lodash-es/internal/arrayMap';
+import property from 'lodash-es/internal/baseProperty';
+
+export default function _filter(eachfn, arr, iterator, callback) {
+ var results = [];
+ eachfn(arr, function (x, index, callback) {
+ iterator(x, function (v) {
+ if (v) {
+ results.push({index: index, value: x});
+ }
+ callback();
+ });
+ }, function () {
+ callback(arrayMap(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), property('value')));
+ });
+}
diff --git a/build/es/internal/findGetResult.js b/build/es/internal/findGetResult.js
new file mode 100644
index 0000000..3aeb07d
--- /dev/null
+++ b/build/es/internal/findGetResult.js
@@ -0,0 +1,5 @@
+'use strict';
+
+export default function _findGetResult(v, x) {
+ return x;
+}
diff --git a/build/es/internal/keyIterator.js b/build/es/internal/keyIterator.js
new file mode 100644
index 0000000..9f12beb
--- /dev/null
+++ b/build/es/internal/keyIterator.js
@@ -0,0 +1,23 @@
+'use strict';
+
+import isArrayLike from 'lodash-es/isArrayLike';
+import keys from 'lodash-es/keys';
+
+export default function keyIterator(coll) {
+ var i = -1;
+ var len;
+ if (isArrayLike(coll)) {
+ len = coll.length;
+ return function next() {
+ i++;
+ return i < len ? i : null;
+ };
+ } else {
+ var okeys = keys(coll);
+ len = okeys.length;
+ return function next() {
+ i++;
+ return i < len ? okeys[i] : null;
+ };
+ }
+}
diff --git a/build/es/internal/map.js b/build/es/internal/map.js
new file mode 100644
index 0000000..5057f49
--- /dev/null
+++ b/build/es/internal/map.js
@@ -0,0 +1,19 @@
+'use strict';
+
+import isArrayLike from 'lodash-es/isArrayLike';
+import noop from 'lodash-es/noop';
+import once from 'lodash-es/once';
+
+export default function _asyncMap(eachfn, arr, iterator, callback) {
+ callback = once(callback || noop);
+ arr = arr || [];
+ var results = isArrayLike(arr) ? [] : {};
+ eachfn(arr, function (value, index, callback) {
+ iterator(value, function (err, v) {
+ results[index] = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+}
diff --git a/build/es/internal/notId.js b/build/es/internal/notId.js
new file mode 100644
index 0000000..d936aab
--- /dev/null
+++ b/build/es/internal/notId.js
@@ -0,0 +1,5 @@
+'use strict';
+
+export default function notId(v) {
+ return !v;
+}
diff --git a/build/es/internal/onlyOnce.js b/build/es/internal/onlyOnce.js
new file mode 100644
index 0000000..f4241c8
--- /dev/null
+++ b/build/es/internal/onlyOnce.js
@@ -0,0 +1,9 @@
+'use strict';
+
+export default function onlyOnce(fn) {
+ return function() {
+ if (fn === null) throw new Error("Callback was already called.");
+ fn.apply(this, arguments);
+ fn = null;
+ };
+}
diff --git a/build/es/internal/parallel.js b/build/es/internal/parallel.js
new file mode 100644
index 0000000..b532908
--- /dev/null
+++ b/build/es/internal/parallel.js
@@ -0,0 +1,22 @@
+'use strict';
+
+import noop from 'lodash-es/noop';
+import isArrayLike from 'lodash-es/isArrayLike';
+import rest from 'lodash-es/rest';
+
+export default function _parallel(eachfn, tasks, callback) {
+ callback = callback || noop;
+ var results = isArrayLike(tasks) ? [] : {};
+
+ eachfn(tasks, function (task, key, callback) {
+ task(rest(function (err, args) {
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[key] = args;
+ callback(err);
+ }));
+ }, function (err) {
+ callback(err, results);
+ });
+}
diff --git a/build/es/internal/queue.js b/build/es/internal/queue.js
new file mode 100644
index 0000000..2e291e3
--- /dev/null
+++ b/build/es/internal/queue.js
@@ -0,0 +1,140 @@
+'use strict';
+
+import arrayEach from 'lodash-es/internal/arrayEach';
+import arrayMap from 'lodash-es/internal/arrayMap';
+import isArray from 'lodash-es/isArray';
+import noop from 'lodash-es/noop';
+import property from 'lodash-es/internal/baseProperty';
+
+import onlyOnce from './onlyOnce';
+import setImmediate from './setImmediate';
+
+export default function queue(worker, concurrency, payload) {
+ if (concurrency == null) {
+ concurrency = 1;
+ }
+ else if(concurrency === 0) {
+ throw new Error('Concurrency must not be zero');
+ }
+ function _insert(q, data, pos, callback) {
+ if (callback != null && typeof callback !== 'function') {
+ throw new Error('task callback must be a function');
+ }
+ q.started = true;
+ if (!isArray(data)) {
+ data = [data];
+ }
+ if(data.length === 0 && q.idle()) {
+ // call drain immediately if there are no tasks
+ return setImmediate(function() {
+ q.drain();
+ });
+ }
+ arrayEach(data, function(task) {
+ var item = {
+ data: task,
+ callback: callback || noop
+ };
+
+ if (pos) {
+ q.tasks.unshift(item);
+ } else {
+ q.tasks.push(item);
+ }
+
+ if (q.tasks.length === q.concurrency) {
+ q.saturated();
+ }
+ });
+ setImmediate(q.process);
+ }
+ function _next(q, tasks) {
+ return function(){
+ workers -= 1;
+
+ var removed = false;
+ var args = arguments;
+ arrayEach(tasks, function (task) {
+ arrayEach(workersList, function (worker, index) {
+ if (worker === task && !removed) {
+ workersList.splice(index, 1);
+ removed = true;
+ }
+ });
+
+ task.callback.apply(task, args);
+ });
+ if (q.tasks.length + workers === 0) {
+ q.drain();
+ }
+ q.process();
+ };
+ }
+
+ var workers = 0;
+ var workersList = [];
+ var q = {
+ tasks: [],
+ concurrency: concurrency,
+ payload: payload,
+ saturated: noop,
+ empty: noop,
+ drain: noop,
+ started: false,
+ paused: false,
+ push: function (data, callback) {
+ _insert(q, data, false, callback);
+ },
+ kill: function () {
+ q.drain = noop;
+ q.tasks = [];
+ },
+ unshift: function (data, callback) {
+ _insert(q, data, true, callback);
+ },
+ process: function () {
+ while(!q.paused && workers < q.concurrency && q.tasks.length){
+
+ var tasks = q.payload ?
+ q.tasks.splice(0, q.payload) :
+ q.tasks.splice(0, q.tasks.length);
+
+ var data = arrayMap(tasks, property('data'));
+
+ if (q.tasks.length === 0) {
+ q.empty();
+ }
+ workers += 1;
+ workersList.push(tasks[0]);
+ var cb = onlyOnce(_next(q, tasks));
+ worker(data, cb);
+ }
+ },
+ length: function () {
+ return q.tasks.length;
+ },
+ running: function () {
+ return workers;
+ },
+ workersList: function () {
+ return workersList;
+ },
+ idle: function() {
+ return q.tasks.length + workers === 0;
+ },
+ pause: function () {
+ q.paused = true;
+ },
+ resume: function () {
+ if (q.paused === false) { return; }
+ q.paused = false;
+ var resumeCount = Math.min(q.concurrency, q.tasks.length);
+ // Need to call q.process once per concurrent
+ // worker to preserve full concurrency after pause
+ for (var w = 1; w <= resumeCount; w++) {
+ setImmediate(q.process);
+ }
+ }
+ };
+ return q;
+}
diff --git a/build/es/internal/reject.js b/build/es/internal/reject.js
new file mode 100644
index 0000000..8b1bf0d
--- /dev/null
+++ b/build/es/internal/reject.js
@@ -0,0 +1,11 @@
+'use strict';
+
+import filter from './filter';
+
+export default function reject(eachfn, arr, iterator, callback) {
+ filter(eachfn, arr, function(value, cb) {
+ iterator(value, function(v) {
+ cb(!v);
+ });
+ }, callback);
+}
diff --git a/build/es/internal/setImmediate.js b/build/es/internal/setImmediate.js
new file mode 100644
index 0000000..c02ad71
--- /dev/null
+++ b/build/es/internal/setImmediate.js
@@ -0,0 +1,19 @@
+'use strict';
+
+var _setImmediate = typeof setImmediate === 'function' && setImmediate;
+
+var _delay;
+if (_setImmediate) {
+ _delay = function(fn) {
+ // not a direct alias for IE10 compatibility
+ _setImmediate(fn);
+ };
+} else if (typeof process === 'object' && typeof process.nextTick === 'function') {
+ _delay = process.nextTick;
+} else {
+ _delay = function(fn) {
+ setTimeout(fn, 0);
+ };
+}
+
+export default _delay;
diff --git a/build/es/internal/withoutIndex.js b/build/es/internal/withoutIndex.js
new file mode 100644
index 0000000..f163ff3
--- /dev/null
+++ b/build/es/internal/withoutIndex.js
@@ -0,0 +1,7 @@
+'use strict';
+
+export default function _withoutIndex(iterator) {
+ return function (value, index, callback) {
+ return iterator(value, callback);
+ };
+}
diff --git a/build/es/iterator.js b/build/es/iterator.js
new file mode 100644
index 0000000..568171a
--- /dev/null
+++ b/build/es/iterator.js
@@ -0,0 +1,17 @@
+'use strict';
+
+export default function(tasks) {
+ function makeCallback(index) {
+ function fn() {
+ if (tasks.length) {
+ tasks[index].apply(null, arguments);
+ }
+ return fn.next();
+ }
+ fn.next = function() {
+ return (index < tasks.length - 1) ? makeCallback(index + 1) : null;
+ };
+ return fn;
+ }
+ return makeCallback(0);
+}
diff --git a/build/es/log.js b/build/es/log.js
new file mode 100644
index 0000000..b581264
--- /dev/null
+++ b/build/es/log.js
@@ -0,0 +1,5 @@
+'use strict';
+
+import consoleFunc from './internal/consoleFunc';
+
+export default consoleFunc('log');
diff --git a/build/es/map.js b/build/es/map.js
new file mode 100644
index 0000000..2a8449c
--- /dev/null
+++ b/build/es/map.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import doParallel from './internal/doParallel';
+import map from './internal/map';
+
+export default doParallel(map);
diff --git a/build/es/mapLimit.js b/build/es/mapLimit.js
new file mode 100644
index 0000000..642b4c6
--- /dev/null
+++ b/build/es/mapLimit.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import doParallelLimit from './internal/doParallelLimit';
+import map from './internal/map';
+
+export default doParallelLimit(map);
diff --git a/build/es/mapSeries.js b/build/es/mapSeries.js
new file mode 100644
index 0000000..bfcdaa2
--- /dev/null
+++ b/build/es/mapSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import map from './internal/map';
+import doSeries from './internal/doSeries';
+
+export default doSeries(map);
diff --git a/build/es/memoize.js b/build/es/memoize.js
new file mode 100644
index 0000000..184f0d6
--- /dev/null
+++ b/build/es/memoize.js
@@ -0,0 +1,36 @@
+'use strict';
+
+import identity from 'lodash-es/identity';
+import rest from 'lodash-es/rest';
+
+import setImmediate from './internal/setImmediate';
+
+export default function memoize(fn, hasher) {
+ var memo = {};
+ var queues = {};
+ hasher = hasher || identity;
+ var memoized = rest(function memoized(args) {
+ var callback = args.pop();
+ var key = hasher.apply(null, args);
+ if (key in memo) {
+ setImmediate(function() {
+ callback.apply(null, memo[key]);
+ });
+ } else if (key in queues) {
+ queues[key].push(callback);
+ } else {
+ queues[key] = [callback];
+ fn.apply(null, args.concat([rest(function(args) {
+ memo[key] = args;
+ var q = queues[key];
+ delete queues[key];
+ for (var i = 0, l = q.length; i < l; i++) {
+ q[i].apply(null, args);
+ }
+ })]));
+ }
+ });
+ memoized.memo = memo;
+ memoized.unmemoized = fn;
+ return memoized;
+}
diff --git a/build/es/nextTick.js b/build/es/nextTick.js
new file mode 100644
index 0000000..b61a8b4
--- /dev/null
+++ b/build/es/nextTick.js
@@ -0,0 +1,7 @@
+'use strict';
+
+import setImmediate from './internal/setImmediate';
+
+var nexTick = typeof process === 'object' && typeof process.nextTick === 'function' ? process.nextTick : setImmediate;
+
+export default nexTick;
diff --git a/build/es/parallel.js b/build/es/parallel.js
new file mode 100644
index 0000000..d3eec16
--- /dev/null
+++ b/build/es/parallel.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import _parallel from './internal/parallel';
+import eachOf from './eachOf';
+
+export default function parallel(tasks, cb) {
+ return _parallel(eachOf, tasks, cb);
+}
diff --git a/build/es/parallelLimit.js b/build/es/parallelLimit.js
new file mode 100644
index 0000000..7e66bed
--- /dev/null
+++ b/build/es/parallelLimit.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import eachOfLimit from './internal/eachOfLimit';
+import parallel from './internal/parallel';
+
+export default function parallelLimit(tasks, limit, cb) {
+ return parallel(eachOfLimit(limit), tasks, cb);
+}
diff --git a/build/es/priorityQueue.js b/build/es/priorityQueue.js
new file mode 100644
index 0000000..9f9d3a0
--- /dev/null
+++ b/build/es/priorityQueue.js
@@ -0,0 +1,72 @@
+'use strict';
+
+import arrayEach from 'lodash-es/internal/arrayEach';
+import isArray from 'lodash-es/isArray';
+import noop from 'lodash-es/noop';
+
+import setImmediate from './setImmediate';
+
+import queue from './queue';
+
+export default function(worker, concurrency) {
+ function _compareTasks(a, b) {
+ return a.priority - b.priority;
+ }
+
+ function _binarySearch(sequence, item, compare) {
+ var beg = -1,
+ end = sequence.length - 1;
+ while (beg < end) {
+ var mid = beg + ((end - beg + 1) >>> 1);
+ if (compare(item, sequence[mid]) >= 0) {
+ beg = mid;
+ } else {
+ end = mid - 1;
+ }
+ }
+ return beg;
+ }
+
+ function _insert(q, data, priority, callback) {
+ if (callback != null && typeof callback !== 'function') {
+ throw new Error('task callback must be a function');
+ }
+ q.started = true;
+ if (!isArray(data)) {
+ data = [data];
+ }
+ if (data.length === 0) {
+ // call drain immediately if there are no tasks
+ return setImmediate(function() {
+ q.drain();
+ });
+ }
+ arrayEach(data, function(task) {
+ var item = {
+ data: task,
+ priority: priority,
+ callback: typeof callback === 'function' ? callback : noop
+ };
+
+ q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
+
+ if (q.tasks.length === q.concurrency) {
+ q.saturated();
+ }
+ setImmediate(q.process);
+ });
+ }
+
+ // Start with a normal queue
+ var q = queue(worker, concurrency);
+
+ // Override push to accept second parameter representing priority
+ q.push = function(data, priority, callback) {
+ _insert(q, data, priority, callback);
+ };
+
+ // Remove unshift function
+ delete q.unshift;
+
+ return q;
+}
diff --git a/build/es/queue.js b/build/es/queue.js
new file mode 100644
index 0000000..de2ac93
--- /dev/null
+++ b/build/es/queue.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import queue from './internal/queue';
+
+export default function (worker, concurrency) {
+ return queue(function (items, cb) {
+ worker(items[0], cb);
+ }, concurrency, 1);
+}
diff --git a/build/es/reduce.js b/build/es/reduce.js
new file mode 100644
index 0000000..51b736a
--- /dev/null
+++ b/build/es/reduce.js
@@ -0,0 +1,14 @@
+'use strict';
+
+import eachOfSeries from './eachOfSeries';
+
+export default function reduce(arr, memo, iterator, cb) {
+ eachOfSeries(arr, function(x, i, cb) {
+ iterator(memo, x, function(err, v) {
+ memo = v;
+ cb(err);
+ });
+ }, function(err) {
+ cb(err, memo);
+ });
+}
diff --git a/build/es/reduceRight.js b/build/es/reduceRight.js
new file mode 100644
index 0000000..730e320
--- /dev/null
+++ b/build/es/reduceRight.js
@@ -0,0 +1,10 @@
+'use strict';
+
+import reduce from './reduce';
+
+var slice = Array.prototype.slice;
+
+export default function reduceRight (arr, memo, iterator, cb) {
+ var reversed = slice.call(arr).reverse();
+ reduce(reversed, memo, iterator, cb);
+}
diff --git a/build/es/reject.js b/build/es/reject.js
new file mode 100644
index 0000000..fb5b87f
--- /dev/null
+++ b/build/es/reject.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import reject from './internal/reject';
+import doParallel from './internal/doParallel';
+
+export default doParallel(reject);
diff --git a/build/es/rejectLimit.js b/build/es/rejectLimit.js
new file mode 100644
index 0000000..7cefed6
--- /dev/null
+++ b/build/es/rejectLimit.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import reject from './internal/reject';
+import doParallelLimit from './internal/doParallelLimit';
+
+export default doParallelLimit(reject);
diff --git a/build/es/rejectSeries.js b/build/es/rejectSeries.js
new file mode 100644
index 0000000..e02adea
--- /dev/null
+++ b/build/es/rejectSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import reject from './internal/reject';
+import doSeries from './internal/doSeries';
+
+export default doSeries(reject);
diff --git a/build/es/retry.js b/build/es/retry.js
new file mode 100644
index 0000000..506a424
--- /dev/null
+++ b/build/es/retry.js
@@ -0,0 +1,77 @@
+'use strict';
+
+import series from './series';
+
+export default function retry(times, task, callback) {
+ var DEFAULT_TIMES = 5;
+ var DEFAULT_INTERVAL = 0;
+
+ var attempts = [];
+
+ var opts = {
+ times: DEFAULT_TIMES,
+ interval: DEFAULT_INTERVAL
+ };
+
+ function parseTimes(acc, t) {
+ if (typeof t === 'number') {
+ acc.times = parseInt(t, 10) || DEFAULT_TIMES;
+ } else if (typeof t === 'object') {
+ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
+ acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
+ } else {
+ throw new Error('Unsupported argument type for \'times\': ' + typeof t);
+ }
+ }
+
+ var length = arguments.length;
+ if (length < 1 || length > 3) {
+ throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
+ } else if (length <= 2 && typeof times === 'function') {
+ callback = task;
+ task = times;
+ }
+ if (typeof times !== 'function') {
+ parseTimes(opts, times);
+ }
+ opts.callback = callback;
+ opts.task = task;
+
+ function wrappedTask(wrappedCallback, wrappedResults) {
+ function retryAttempt(task, finalAttempt) {
+ return function(seriesCallback) {
+ task(function(err, result) {
+ seriesCallback(!err || finalAttempt, {
+ err: err,
+ result: result
+ });
+ }, wrappedResults);
+ };
+ }
+
+ function retryInterval(interval) {
+ return function(seriesCallback) {
+ setTimeout(function() {
+ seriesCallback(null);
+ }, interval);
+ };
+ }
+
+ while (opts.times) {
+
+ var finalAttempt = !(opts.times -= 1);
+ attempts.push(retryAttempt(opts.task, finalAttempt));
+ if (!finalAttempt && opts.interval > 0) {
+ attempts.push(retryInterval(opts.interval));
+ }
+ }
+
+ series(attempts, function(done, data) {
+ data = data[data.length - 1];
+ (wrappedCallback || opts.callback)(data.err, data.result);
+ });
+ }
+
+ // If a callback is passed, run this as a controll flow
+ return opts.callback ? wrappedTask() : wrappedTask;
+}
diff --git a/build/es/seq.js b/build/es/seq.js
new file mode 100644
index 0000000..c9e02c1
--- /dev/null
+++ b/build/es/seq.js
@@ -0,0 +1,28 @@
+'use strict';
+
+import noop from 'lodash-es/noop';
+import rest from 'lodash-es/rest';
+import reduce from './reduce';
+
+export default function seq( /* functions... */ ) {
+ var fns = arguments;
+ return rest(function(args) {
+ var that = this;
+
+ var cb = args[args.length - 1];
+ if (typeof cb == 'function') {
+ args.pop();
+ } else {
+ cb = noop;
+ }
+
+ reduce(fns, args, function(newargs, fn, cb) {
+ fn.apply(that, newargs.concat([rest(function(err, nextargs) {
+ cb(err, nextargs);
+ })]));
+ },
+ function(err, results) {
+ cb.apply(that, [err].concat(results));
+ });
+ });
+}
diff --git a/build/es/series.js b/build/es/series.js
new file mode 100644
index 0000000..bd8e15d
--- /dev/null
+++ b/build/es/series.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import parallel from './internal/parallel';
+import eachOfSeries from './eachOfSeries';
+
+export default function series(tasks, cb) {
+ return parallel(eachOfSeries, tasks, cb);
+}
diff --git a/build/es/setImmediate.js b/build/es/setImmediate.js
new file mode 100644
index 0000000..05d9555
--- /dev/null
+++ b/build/es/setImmediate.js
@@ -0,0 +1,5 @@
+'use strict';
+
+import setImmediate from './internal/setImmediate';
+
+export default setImmediate;
diff --git a/build/es/some.js b/build/es/some.js
new file mode 100644
index 0000000..46532b7
--- /dev/null
+++ b/build/es/some.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import identity from 'lodash-es/identity';
+
+import createTester from './internal/createTester';
+import eachOf from './eachOf';
+
+export default createTester(eachOf, Boolean, identity);
diff --git a/build/es/someLimit.js b/build/es/someLimit.js
new file mode 100644
index 0000000..6c17067
--- /dev/null
+++ b/build/es/someLimit.js
@@ -0,0 +1,7 @@
+'use strict';
+
+import createTester from './internal/createTester';
+import eachOfLimit from './eachOfLimit';
+import identity from 'lodash-es/identity';
+
+export default createTester(eachOfLimit, Boolean, identity);
diff --git a/build/es/sortBy.js b/build/es/sortBy.js
new file mode 100644
index 0000000..b4c8b8e
--- /dev/null
+++ b/build/es/sortBy.js
@@ -0,0 +1,23 @@
+'use strict';
+
+import arrayMap from 'lodash-es/internal/arrayMap';
+import property from 'lodash-es/internal/baseProperty';
+
+import map from './map';
+
+export default function sortBy (arr, iterator, cb) {
+ map(arr, function (x, cb) {
+ iterator(x, function (err, criteria) {
+ if (err) return cb(err);
+ cb(null, {value: x, criteria: criteria});
+ });
+ }, function (err, results) {
+ if (err) return cb(err);
+ cb(null, arrayMap(results.sort(comparator), property('value')));
+ });
+
+ function comparator(left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ }
+}
diff --git a/build/es/times.js b/build/es/times.js
new file mode 100644
index 0000000..da2b31f
--- /dev/null
+++ b/build/es/times.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import map from './map';
+import range from 'lodash-es/internal/baseRange';
+
+export default function (count, iterator, callback) {
+ map(range(0, count, 1), iterator, callback);
+}
diff --git a/build/es/timesLimit.js b/build/es/timesLimit.js
new file mode 100644
index 0000000..9c2feca
--- /dev/null
+++ b/build/es/timesLimit.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import mapLimit from './mapLimit';
+import range from 'lodash-es/internal/baseRange';
+
+export default function timeLimit(count, limit, iterator, cb) {
+ return mapLimit(range(0, count, 1), limit, iterator, cb);
+}
diff --git a/build/es/timesSeries.js b/build/es/timesSeries.js
new file mode 100644
index 0000000..ebcb345
--- /dev/null
+++ b/build/es/timesSeries.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import mapSeries from './mapSeries';
+import range from 'lodash-es/internal/baseRange';
+
+export default function (count, iterator, callback) {
+ mapSeries(range(0, count, 1), iterator, callback);
+}
diff --git a/build/es/transform.js b/build/es/transform.js
new file mode 100644
index 0000000..7b80fca
--- /dev/null
+++ b/build/es/transform.js
@@ -0,0 +1,19 @@
+'use strict';
+
+import isArray from 'lodash-es/isArray';
+
+import eachOf from './eachOf';
+
+export default function transform (arr, memo, iterator, callback) {
+ if (arguments.length === 3) {
+ callback = iterator;
+ iterator = memo;
+ memo = isArray(arr) ? [] : {};
+ }
+
+ eachOf(arr, function(v, k, cb) {
+ iterator(memo, v, k, cb);
+ }, function(err) {
+ callback(err, memo);
+ });
+}
diff --git a/build/es/unmemoize.js b/build/es/unmemoize.js
new file mode 100644
index 0000000..d652e7b
--- /dev/null
+++ b/build/es/unmemoize.js
@@ -0,0 +1,7 @@
+'use strict';
+
+export default function unmemoize(fn) {
+ return function () {
+ return (fn.unmemoized || fn).apply(null, arguments);
+ };
+}
diff --git a/build/es/until.js b/build/es/until.js
new file mode 100644
index 0000000..f9ed2fd
--- /dev/null
+++ b/build/es/until.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import whilst from './whilst';
+
+export default function until(test, iterator, cb) {
+ return whilst(function() {
+ return !test.apply(this, arguments);
+ }, iterator, cb);
+}
diff --git a/build/es/waterfall.js b/build/es/waterfall.js
new file mode 100644
index 0000000..c629bcf
--- /dev/null
+++ b/build/es/waterfall.js
@@ -0,0 +1,32 @@
+'use strict';
+
+import isArray from 'lodash-es/isArray';
+import noop from 'lodash-es/noop';
+import once from 'lodash-es/once';
+import rest from 'lodash-es/rest';
+
+import ensureAsync from './ensureAsync';
+import iterator from './iterator';
+
+export default function(tasks, cb) {
+ cb = once(cb || noop);
+ if (!isArray(tasks)) return cb(new Error('First argument to waterfall must be an array of functions'));
+ if (!tasks.length) return cb();
+
+ function wrapIterator(iterator) {
+ return rest(function(err, args) {
+ if (err) {
+ cb.apply(null, [err].concat(args));
+ } else {
+ var next = iterator.next();
+ if (next) {
+ args.push(wrapIterator(next));
+ } else {
+ args.push(cb);
+ }
+ ensureAsync(iterator).apply(null, args);
+ }
+ });
+ }
+ wrapIterator(iterator(tasks))();
+}
diff --git a/build/es/whilst.js b/build/es/whilst.js
new file mode 100644
index 0000000..2f5c2ef
--- /dev/null
+++ b/build/es/whilst.js
@@ -0,0 +1,15 @@
+'use strict';
+
+import noop from 'lodash-es/noop';
+import rest from 'lodash-es/rest';
+
+export default function whilst(test, iterator, cb) {
+ cb = cb || noop;
+ if (!test()) return cb(null);
+ var next = rest(function(err, args) {
+ if (err) return cb(err);
+ if (test.apply(this, args)) return iterator(next);
+ cb.apply(null, [null].concat(args));
+ });
+ iterator(next);
+}
diff --git a/build/package.json b/build/package.json
new file mode 100644
index 0000000..2e0b63b
--- /dev/null
+++ b/build/package.json
@@ -0,0 +1,97 @@
+{
+ "name": "async",
+ "description": "Higher-order functions and common patterns for asynchronous code",
+ "version": "2.0.0-alpha",
+ "main": "index.js",
+ "esnext:main": "es/index.js",
+ "author": "Caolan McMahon",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/caolan/async.git"
+ },
+ "bugs": {
+ "url": "https://github.com/caolan/async/issues"
+ },
+ "keywords": [
+ "async",
+ "callback",
+ "module",
+ "utility"
+ ],
+ "dependencies": {
+ "lodash": "^4.0.0",
+ "lodash-es": "^4.0.0"
+ },
+ "devDependencies": {
+ "babel-cli": "^6.3.17",
+ "babel-core": "^6.3.26",
+ "babel-plugin-add-module-exports": "~0.1.2",
+ "babel-plugin-transform-es2015-modules-commonjs": "^6.3.16",
+ "babel-preset-es2015": "^6.3.13",
+ "babelify": "^7.2.0",
+ "benchmark": "bestiejs/benchmark.js",
+ "bluebird": "^2.9.32",
+ "chai": "^3.1.0",
+ "coveralls": "^2.11.2",
+ "es6-promise": "^2.3.0",
+ "fs-extra": "^0.26.3",
+ "gulp": "~3.9.0",
+ "jscs": "^1.13.1",
+ "jshint": "~2.8.0",
+ "karma": "^0.13.2",
+ "karma-browserify": "^4.2.1",
+ "karma-firefox-launcher": "^0.1.6",
+ "karma-mocha": "^0.2.0",
+ "karma-mocha-reporter": "^1.0.2",
+ "mocha": "^2.2.5",
+ "native-promise-only": "^0.8.0-a",
+ "nodeunit": ">0.0.0",
+ "nyc": "^2.1.0",
+ "recursive-readdir": "^1.3.0",
+ "rimraf": "^2.5.0",
+ "rollup": "^0.25.0",
+ "rollup-plugin-npm": "~1.3.0",
+ "rsvp": "^3.0.18",
+ "semver": "^4.3.6",
+ "uglify-js": "~2.4.0",
+ "vinyl-buffer": "~1.0.0",
+ "vinyl-source-stream": "~1.1.0",
+ "xyz": "^0.5.0",
+ "yargs": "~3.9.1"
+ },
+ "scripts": {
+ "coverage": "nyc npm test && nyc report",
+ "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls",
+ "lint": "jshint lib/ test/ mocha_test/ perf/memory.js perf/suites.js perf/benchmark.js support/ gulpfile.js karma.conf.js && jscs lib/ test/ mocha_test/ perf/memory.js perf/suites.js perf/benchmark.js support/ gulpfile.js karma.conf.js",
+ "mocha-browser-test": "karma start",
+ "mocha-node-test": "mocha mocha_test/ --compilers js:babel-core/register",
+ "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test",
+ "nodeunit-test": "nodeunit test/test-async.js",
+ "test": "npm run-script lint && npm run nodeunit-test && npm run mocha-test"
+ },
+ "license": "MIT",
+ "jam": {
+ "main": "async.js",
+ "include": [
+ "async.js",
+ "README.md",
+ "LICENSE"
+ ],
+ "categories": [
+ "Utilities"
+ ]
+ },
+ "spm": {
+ "main": "async.js"
+ },
+ "volo": {
+ "main": "async.js",
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "test",
+ "tests"
+ ]
+ }
+}
diff --git a/component.json b/component.json
index 5b05149..b699237 100644
--- a/component.json
+++ b/component.json
@@ -1,17 +1,17 @@
{
"name": "async",
"description": "Higher-order functions and common patterns for asynchronous code",
- "version": "1.5.0",
+ "version": "2.0.0-alpha",
"keywords": [
"async",
"callback",
- "utility",
- "module"
+ "module",
+ "utility"
],
"license": "MIT",
- "main": "lib/async.js",
+ "main": "index.js",
"repository": "caolan/async",
"scripts": [
- "lib/async.js"
+ "index.js"
]
-}
+} \ No newline at end of file
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..0d0b270
--- /dev/null
+++ b/index.js
@@ -0,0 +1 @@
+module.exports = require("./build/")
diff --git a/package.json b/package.json
index c0fbf4d..756ad2b 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,8 @@
"name": "async",
"description": "Higher-order functions and common patterns for asynchronous code",
"version": "2.0.0-alpha",
- "main": "lib/async.js",
+ "main": "index.js",
+ "esnext:main": "es/index.js",
"author": "Caolan McMahon",
"repository": {
"type": "git",
@@ -58,11 +59,6 @@
"xyz": "^0.5.0",
"yargs": "~3.9.1"
},
- "files": [
- "dist/async.js",
- "dist/async.min.js",
- "lib"
- ],
"scripts": {
"coverage": "nyc npm test && nyc report",
"coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls",
@@ -75,27 +71,27 @@
},
"license": "MIT",
"jam": {
- "categories": [
- "Utilities"
- ],
+ "main": "index.js",
"include": [
- "LICENSE",
+ "lib/async.js",
"README.md",
- "lib/async.js"
+ "LICENSE"
],
- "main": "lib/async.js"
+ "categories": [
+ "Utilities"
+ ]
},
"spm": {
- "main": "lib/async.js"
+ "main": "index.js"
},
"volo": {
+ "main": "index.js",
"ignore": [
"**/.*",
- "bower_components",
"node_modules",
+ "bower_components",
"test",
"tests"
- ],
- "main": "lib/async.js"
+ ]
}
-}
+} \ No newline at end of file