summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSteve Robb <softnfuzzyrobb@gmail.com>2016-03-06 18:06:13 +0000
committerSteve Robb <softnfuzzyrobb@gmail.com>2016-03-06 18:06:13 +0000
commit20c0a9be73f517fcb7cda940675007416bb3aa0c (patch)
tree3cd0ca42c3375dd1c61c92ed0f6496631cc2ffad
parent0858e09f203f9e358bdfa1ce84400e758bea68fc (diff)
parentf38483cbccc16efe205b0bf1439c233e61a7f090 (diff)
downloadasync-20c0a9be73f517fcb7cda940675007416bb3aa0c.tar.gz
Merge branch 'master' into autoInjectPR
Conflicts: README.md lib/async.js test/test-async.js
-rw-r--r--.babelrc3
-rw-r--r--.editorconfig17
-rw-r--r--.gitignore6
-rw-r--r--.gitmodules9
-rw-r--r--.jscsrc5
-rw-r--r--.jshintrc5
-rw-r--r--.npmignore4
-rw-r--r--CHANGELOG.md5
-rw-r--r--LICENSE2
-rw-r--r--Makefile120
-rw-r--r--README.md732
-rw-r--r--bower.json28
-rw-r--r--component.json12
-rw-r--r--dist/async.js3755
-rw-r--r--dist/async.min.js2
-rw-r--r--dist/async.min.map2
-rw-r--r--gulpfile.js89
-rw-r--r--index.js3
-rw-r--r--karma.conf.js29
-rw-r--r--lib/apply.js9
-rw-r--r--lib/applyEach.js6
-rw-r--r--lib/applyEachSeries.js6
-rwxr-xr-xlib/async.js1310
-rw-r--r--lib/asyncify.js26
-rw-r--r--lib/auto.js135
-rw-r--r--lib/cargo.js7
-rw-r--r--lib/compose.js9
-rw-r--r--lib/concat.js6
-rw-r--r--lib/concatSeries.js6
-rw-r--r--lib/constant.js10
-rw-r--r--lib/detect.js9
-rw-r--r--lib/detectLimit.js9
-rw-r--r--lib/detectSeries.js9
-rw-r--r--lib/dir.js5
-rw-r--r--lib/doDuring.js12
-rw-r--r--lib/doUntil.js9
-rw-r--r--lib/doWhilst.js10
-rw-r--r--lib/during.js25
-rw-r--r--lib/each.js6
-rw-r--r--lib/eachLimit.js9
-rw-r--r--lib/eachOf.js6
-rw-r--r--lib/eachOfLimit.js7
-rw-r--r--lib/eachOfSeries.js6
-rw-r--r--lib/eachSeries.js6
-rw-r--r--lib/ensureAsync.js24
-rw-r--r--lib/every.js6
-rw-r--r--lib/everyLimit.js7
-rw-r--r--lib/filter.js6
-rw-r--r--lib/filterLimit.js6
-rw-r--r--lib/filterSeries.js6
-rw-r--r--lib/forever.js17
-rw-r--r--lib/index.js231
-rw-r--r--lib/internal/applyEach.js22
-rw-r--r--lib/internal/concat.js13
-rw-r--r--lib/internal/consoleFunc.js23
-rw-r--r--lib/internal/createTester.js37
-rw-r--r--lib/internal/doLimit.js7
-rw-r--r--lib/internal/doParallel.js9
-rw-r--r--lib/internal/doParallelLimit.js9
-rw-r--r--lib/internal/doSeries.js9
-rw-r--r--lib/internal/eachOfLimit.js49
-rw-r--r--lib/internal/filter.js30
-rw-r--r--lib/internal/findGetResult.js5
-rw-r--r--lib/internal/keyIterator.js23
-rw-r--r--lib/internal/map.js19
-rw-r--r--lib/internal/notId.js5
-rw-r--r--lib/internal/onlyOnce.js9
-rw-r--r--lib/internal/parallel.js22
-rw-r--r--lib/internal/queue.js145
-rw-r--r--lib/internal/reject.js15
-rw-r--r--lib/internal/setImmediate.js19
-rw-r--r--lib/internal/withoutIndex.js7
-rw-r--r--lib/iterator.js17
-rw-r--r--lib/log.js5
-rw-r--r--lib/map.js6
-rw-r--r--lib/mapLimit.js6
-rw-r--r--lib/mapSeries.js6
-rw-r--r--lib/memoize.js37
-rw-r--r--lib/nextTick.js7
-rw-r--r--lib/parallel.js6
-rw-r--r--lib/parallelLimit.js8
-rw-r--r--lib/priorityQueue.js75
-rw-r--r--lib/queue.js9
-rw-r--r--lib/race.js14
-rw-r--r--lib/reduce.js14
-rw-r--r--lib/reduceRight.js10
-rw-r--r--lib/reject.js6
-rw-r--r--lib/rejectLimit.js6
-rw-r--r--lib/rejectSeries.js6
-rw-r--r--lib/retry.js77
-rw-r--r--lib/seq.js28
-rw-r--r--lib/series.js8
-rw-r--r--lib/setImmediate.js5
-rw-r--r--lib/some.js6
-rw-r--r--lib/someLimit.js7
-rw-r--r--lib/sortBy.js23
-rw-r--r--lib/times.js6
-rw-r--r--lib/timesLimit.js8
-rw-r--r--lib/timesSeries.js6
-rw-r--r--lib/transform.js19
-rw-r--r--lib/unmemoize.js7
-rw-r--r--lib/until.js9
-rw-r--r--lib/waterfall.js32
-rw-r--r--lib/whilst.js15
-rw-r--r--mocha_test/auto.js347
-rw-r--r--mocha_test/compose.js2
-rw-r--r--mocha_test/detect.js123
-rw-r--r--mocha_test/every.js90
-rw-r--r--mocha_test/filter.js132
-rw-r--r--mocha_test/forever.js2
-rw-r--r--mocha_test/mocha.opts4
-rw-r--r--mocha_test/priorityQueue.js70
-rw-r--r--mocha_test/queue.js69
-rw-r--r--mocha_test/race.js70
-rw-r--r--mocha_test/some.js91
-rw-r--r--package.json74
-rw-r--r--support/build.test.js96
-rw-r--r--support/build/aggregate-build.js20
-rw-r--r--support/build/aggregate-bundle.js9
-rw-r--r--support/build/aggregate-cjs.js9
-rw-r--r--support/build/compile-modules.js45
-rw-r--r--support/build/modules-cjs.js3
-rw-r--r--support/build/plugin-lodash-import-rename.js24
-rw-r--r--support/es.test.js21
-rw-r--r--support/module_template.md13
-rwxr-xr-xsupport/sync-cjs-package.js10
-rwxr-xr-xsupport/sync-es-package.js15
-rwxr-xr-xsupport/sync-package-managers.js30
-rwxr-xr-xsupport/xyz.sh171
-rwxr-xr-xtest/test-async.js1091
-rw-r--r--test/test.html2
131 files changed, 6405 insertions, 3988 deletions
diff --git a/.babelrc b/.babelrc
new file mode 100644
index 0000000..c13c5f6
--- /dev/null
+++ b/.babelrc
@@ -0,0 +1,3 @@
+{
+ "presets": ["es2015"]
+}
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..44b5d31
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,17 @@
+# editorconfig.org
+root = true
+
+[*]
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+indent_style = space
+indent_size = 4
+
+[package.json]
+indent_size = 2
+
+[Makefile]
+indent_style = tab
+indent_size = 4
diff --git a/.gitignore b/.gitignore
index 9134974..1f05292 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,10 @@
node_modules
-dist
perf/versions
nyc_output
coverage
*.log
+.DS_Store
+npm-debug.log
+tmp
+build
+build-es
diff --git a/.gitmodules b/.gitmodules
deleted file mode 100644
index a9aae98..0000000
--- a/.gitmodules
+++ /dev/null
@@ -1,9 +0,0 @@
-[submodule "deps/nodeunit"]
- path = deps/nodeunit
- url = git://github.com/caolan/nodeunit.git
-[submodule "deps/UglifyJS"]
- path = deps/UglifyJS
- url = https://github.com/mishoo/UglifyJS.git
-[submodule "deps/nodelint"]
- path = deps/nodelint
- url = https://github.com/tav/nodelint.git
diff --git a/.jscsrc b/.jscsrc
index b8cfa17..3e93b59 100644
--- a/.jscsrc
+++ b/.jscsrc
@@ -1,3 +1,4 @@
{
- "validateIndentation": 4
-} \ No newline at end of file
+ "validateIndentation": 4,
+ "esnext": true
+}
diff --git a/.jshintrc b/.jshintrc
index 76be34a..375fbdf 100644
--- a/.jshintrc
+++ b/.jshintrc
@@ -9,6 +9,7 @@
"trailing": true,
"evil": true,
"laxcomma": true,
+ "esnext": true,
// Relaxing options
"onevar": false,
@@ -24,6 +25,8 @@
"define": true,
"describe": true,
"context": true,
- "it": true
+ "it": true,
+ "before": true,
+ "after": true
}
}
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000..4274f79
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,4 @@
+lib
+scripts
+support/dependencies.json
+support/module_template.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa32563..3dc4946 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,8 @@
+# v1.5.2
+- Allow using `"constructor"` as an argument in `memoize` (#998)
+- Give a better error messsage when `auto` dependency checking fails (#994)
+- Various doc updates (#936, #956, #979, #1002)
+
# v1.5.1
- Fix issue with `pause` in `queue` with concurrency enabled (#946)
- `while` and `until` now pass the final result to callback (#963)
diff --git a/LICENSE b/LICENSE
index 8f29698..9fe85b9 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2010-2014 Caolan McMahon
+Copyright (c) 2010-2016 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
diff --git a/Makefile b/Makefile
index 87279f4..80e8f52 100644
--- a/Makefile
+++ b/Makefile
@@ -1,37 +1,123 @@
+# This makefile is meant to be run on OSX/Linux. Make sure any artifacts
+# created here are checked in so people on all platforms can run npm scripts.
+# This build should be run once per release.
+
export PATH := ./node_modules/.bin/:$(PATH):./bin/
PACKAGE = asyncjs
-XYZ = node_modules/.bin/xyz --repo git@github.com:caolan/async.git
+REQUIRE_NAME = async
+BABEL_NODE = babel-node
+UGLIFY = uglifyjs
+XYZ = support/xyz.sh --repo git@github.com:caolan/async.git
+
+BUILDDIR = build
+BUILD_ES = build-es
+DIST = dist
+SRC = lib/index.js
+SCRIPTS = ./support
+JS_SRC = $(shell find lib/ -type f -name '*.js')
+LINT_FILES = lib/ test/ mocha_test/ $(shell find perf/ -maxdepth 2 -type f) support/ gulpfile.js karma.conf.js
-BUILDDIR = dist
-SRC = lib/async.js
+UMD_BUNDLE = $(BUILDDIR)/dist/async.js
+UMD_BUNDLE_MIN = $(BUILDDIR)/dist/async.min.js
+CJS_BUNDLE = $(BUILDDIR)/index.js
+ES_MODULES = $(patsubst lib/%.js, build-es/%.js, $(JS_SRC))
-all: lint test clean build
-build: $(wildcard lib/*.js)
- mkdir -p $(BUILDDIR)
- cp $(SRC) $(BUILDDIR)/async.js
- uglifyjs $(BUILDDIR)/async.js -mc \
- --source-map $(BUILDDIR)/async.min.map \
- -o $(BUILDDIR)/async.min.js
+all: clean lint build test
test:
- nodeunit test
+ npm test
clean:
rm -rf $(BUILDDIR)
+ rm -rf $(BUILD_ES)
+ rm -rf $(DIST)
+ rm -rf tmp/
lint:
- jshint $(SRC) test/*.js mocha_test/* perf/*.js
- jscs $(SRC) test/*.js mocha_test/* perf/*.js
+ jshint $(LINT_FILES)
+ jscs $(LINT_FILES)
-.PHONY: test lint build all clean
+# Compile the ES6 modules to singular bundles, and individual bundles
+build-bundle: build-modules $(UMD_BUNDLE) $(CJS_BUNDLE)
+
+build-modules:
+ $(BABEL_NODE) $(SCRIPTS)/build/modules-cjs.js
+
+$(UMD_BUNDLE): $(JS_SRC) package.json
+ mkdir -p "$(@D)"
+ $(BABEL_NODE) $(SCRIPTS)/build/aggregate-bundle.js
+
+$(CJS_BUNDLE): $(JS_SRC) package.json
+ $(BABEL_NODE) $(SCRIPTS)/build/aggregate-cjs.js
+
+# Create the minified UMD versions and copy them to dist/ for bower
+build-dist: $(DIST) $(UMD_BUNDLE) $(UMD_BUNDLE_MIN) $(DIST)/async.js $(DIST)/async.min.js
+
+$(DIST):
+ mkdir -p $@
+
+$(UMD_BUNDLE_MIN): $(UMD_BUNDLE)
+ mkdir -p "$(@D)"
+ $(UGLIFY) $< --mangle --compress \
+ --source-map $(DIST)/async.min.map \
+ -o $@
+
+$(DIST)/async.js: $(UMD_BUNDLE)
+ cp $< $@
+
+$(DIST)/async.min.js: $(UMD_BUNDLE_MIN)
+ cp $< $@
+
+build-es: $(ES_MODULES)
+
+$(BUILD_ES)/%.js: lib/%.js
+ mkdir -p "$(@D)"
+ sed -r "s/(import.+)lodash/\1lodash-es/g" $< > $@
+test-build:
+ mocha support/build.test.js
+
+build-config: $(BUILDDIR)/package.json $(BUILDDIR)/component.json $(BUILDDIR)/bower.json $(BUILDDIR)/README.md $(BUILDDIR)/LICENSE $(BUILDDIR)/CHANGELOG.md
+
+build-es-config: $(BUILD_ES)/package.json $(BUILD_ES)/README.md $(BUILD_ES)/LICENSE $(BUILD_ES)/CHANGELOG.md
+
+bower.json: package.json
+ support/sync-package-managers.js
+
+component.json: package.json
+ support/sync-package-managers.js
+
+$(BUILDDIR)/package.json: package.json
+ mkdir -p "$(@D)"
+ support/sync-cjs-package.js > $@
+
+$(BUILDDIR)/%: %
+ mkdir -p "$(@D)"
+ cp $< $@
+
+$(BUILD_ES)/package.json: package.json
+ mkdir -p "$(@D)"
+ support/sync-es-package.js > $@
+
+$(BUILD_ES)/%: %
+ mkdir -p "$(@D)"
+ cp $< $@
+
+.PHONY: build-modules build-bundle build-dist build-es build-config build-es-config test-build
+
+build: clean build-bundle build-dist build-es build-config build-es-config test-build
+
+.PHONY: test lint build all clean
.PHONY: release-major release-minor release-patch
release-major release-minor release-patch: all
- ./support/sync-package-managers.js
- git add --force *.json
- git add --force $(BUILDDIR)
+ git add --force $(DIST)
git commit -am "update minified build"; true
$(XYZ) --increment $(@:release-%=%)
+ # build again to propagate the version
+ $(MAKE) build-config
+ $(MAKE) build-es-config
+ cd build/ && npm pack
+ cd build-es/ && npm pack
diff --git a/README.md b/README.md
index 0d75594..562a27b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,7 @@
-# Async.js
+NOTE: This is the README for Async 2.0, currently under development. There are some differences with the current stable version. For docs for async@1.5.2 go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md).
+-------------------------
+
+# Async.js v2.0.0-pre
[![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)
@@ -14,8 +17,7 @@ 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`
+- [component](https://github.com/component/component): `component install caolan/async`
- [jam](http://jamjs.org/): `jam install async`
- [spm](http://spmjs.io/): `spm install async`
@@ -28,12 +30,16 @@ callback as the last argument of your `async` function.
## Quick Examples
-```javascript
+```js
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){
+async.filter(['file1','file2','file3'], function(filePath, callback) {
+ fs.access(filePath, function(err) {
+ callback(null, !err)
+ });
+}, function(results){
// results now equals an array of the existing files
});
@@ -55,33 +61,33 @@ 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.
+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 iteratee. 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);
- }
+async.eachSeries(hugeArray, function iteratee(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.eachSeries(hugeArray, function iteratee(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.
@@ -97,13 +103,13 @@ Make sure to always `return` when calling a callback early, otherwise you will c
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);
+ 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
@@ -113,37 +119,37 @@ async.waterfall([
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
+### Binding a context to an iteratee
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:
+make `async` execute your iteratees in a given context, or are confused as to why
+a method of another library isn't working as an iteratee, 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);
- }
+ 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.
+ // 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.
+ // result is [1, 4, 9]
+ // With the help of bind we can attach a context to the iteratee 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.
});
```
@@ -217,6 +223,7 @@ Some functions are also available in the following forms:
* [`retry`](#retry)
* [`iterator`](#iterator)
* [`times`](#times), `timesSeries`, `timesLimit`
+* [`race`](#race)
### Utils
@@ -234,27 +241,27 @@ Some functions are also available in the following forms:
## Collections
-<a name="forEach" />
-<a name="each" />
-### each(arr, iterator, [callback])
+<a name="forEach"></a>
+<a name="each"></a>
+### each(arr, iteratee, [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
+Applies the function `iteratee` to each item in `arr`, in parallel.
+The `iteratee` is called with an item from the list, and a callback for when it
+has finished. If the `iteratee` 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.
+Note, that since this function applies `iteratee` to each item in parallel,
+there is no guarantee that the iteratee 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
+* `iteratee(item, callback)` - A function to apply to each item in `arr`.
+ The iteratee 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
+ to the iteratee. If you need the index, use [`forEachOf`](#forEachOf).
+* `callback(err)` - *Optional* A callback which is called when all `iteratee` functions
have finished, or an error occurs.
__Examples__
@@ -299,27 +306,26 @@ async.each(openFiles, function(file, callback) {
__Related__
-* eachSeries(arr, iterator, [callback])
-* eachLimit(arr, limit, iterator, [callback])
+* eachSeries(arr, iteratee, [callback])
+* eachLimit(arr, limit, iteratee, [callback])
---------------------------------------
-<a name="forEachOf" />
-<a name="eachOf" />
-
-### forEachOf(obj, iterator, [callback])
+<a name="forEachOf"></a>
+<a name="eachOf"></a>
+### forEachOf(obj, iteratee, [callback])
-Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator.
+Like `each`, except that it iterates over objects, and passes the key as the second argument to the iteratee.
__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
+* `iteratee(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 iteratee 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.
+* `callback(err)` - *Optional* A callback which is called when all `iteratee` functions have finished, or an error occurs.
__Example__
@@ -328,49 +334,49 @@ 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();
- })
+ 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);
+ 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])
+* forEachOfSeries(obj, iteratee, [callback])
+* forEachOfLimit(obj, limit, iteratee, [callback])
---------------------------------------
-<a name="map" />
-### map(arr, iterator, [callback])
+<a name="map"></a>
+### map(arr, iteratee, [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
+the `iteratee` function. The `iteratee` 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
+an `error`, and the transformed item from `arr`. If `iteratee` 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.
+Note, that since this function applies the `iteratee` to each item in parallel,
+there is no guarantee that the `iteratee` 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
+* `iteratee(item, callback)` - A function to apply to each item in `arr`.
+ The iteratee 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`
+* `callback(err, results)` - *Optional* A callback which is called when all `iteratee`
functions have finished, or an error occurs. Results is an array of the
transformed items from the `arr`.
@@ -383,66 +389,68 @@ async.map(['file1','file2','file3'], fs.stat, function(err, results){
```
__Related__
-* mapSeries(arr, iterator, [callback])
-* mapLimit(arr, limit, iterator, [callback])
+
+* mapSeries(arr, iteratee, [callback])
+* mapLimit(arr, limit, iteratee, [callback])
---------------------------------------
-<a name="select" />
-<a name="filter" />
-### filter(arr, iterator, [callback])
+<a name="select"></a>
+<a name="filter"></a>
+### filter(arr, iteratee, [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.
+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
+* `iteratee(item, callback)` - A truth test to apply to each item in `arr`.
+ The `iteratee` is passed a `callback(err, 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`
+* `callback(err, results)` - *Optional* A callback which is called after all the `iteratee`
functions have finished.
__Example__
```js
-async.filter(['file1','file2','file3'], fs.exists, function(results){
+async.filter(['file1','file2','file3'], function(filePath, callback) {
+ fs.access(filePath, function(err) {
+ callback(null, !err)
+ });
+}, function(results){
// results now equals an array of the existing files
});
```
__Related__
-* filterSeries(arr, iterator, [callback])
-* filterLimit(arr, limit, iterator, [callback])
+* filterSeries(arr, iteratee, [callback])
+* filterLimit(arr, limit, iteratee, [callback])
---------------------------------------
-<a name="reject" />
-### reject(arr, iterator, [callback])
+<a name="reject"></a>
+### reject(arr, iteratee, [callback])
The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
__Related__
-* rejectSeries(arr, iterator, [callback])
-* rejectLimit(arr, limit, iterator, [callback])
+* rejectSeries(arr, iteratee, [callback])
+* rejectLimit(arr, limit, iteratee, [callback])
---------------------------------------
-<a name="reduce" />
-### reduce(arr, memo, iterator, [callback])
+<a name="reduce"></a>
+### reduce(arr, memo, iteratee, [callback])
__Aliases:__ `inject`, `foldl`
-Reduces `arr` into a single value using an async `iterator` to return
+Reduces `arr` into a single value using an async `iteratee` to return
each successive step. `memo` is the initial state of the reduction.
This function only operates in series.
@@ -455,13 +463,13 @@ __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
+* `iteratee(memo, item, callback)` - A function applied to each item in the
+ array to produce the next step in the reduction. The `iteratee` 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`
+* `callback(err, result)` - *Optional* A callback which is called after all the `iteratee`
functions have finished. Result is the reduced value.
__Example__
@@ -479,67 +487,70 @@ async.reduce([1,2,3], 0, function(memo, item, callback){
---------------------------------------
-<a name="reduceRight" />
-### reduceRight(arr, memo, iterator, [callback])
+<a name="reduceRight"></a>
+### reduceRight(arr, memo, iteratee, [callback])
__Alias:__ `foldr`
Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
-
---------------------------------------
-<a name="detect" />
-### detect(arr, iterator, [callback])
+<a name="detect"></a>
+### detect(arr, iteratee, [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
+`iteratee` is applied in parallel, meaning the first iteratee 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).
+If order within the original `arr` is important, then look at `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.**
+* `iteratee(item, callback)` - A truth test to apply to each item in `arr`.
+ The iteratee is passed a `callback(err, truthValue)` which must be called with a
+ boolean argument once it has completed.
+* `callback(err, result)` - *Optional* A callback which is called as soon as any iteratee returns
+ `true`, or after all the `iteratee` functions have finished. Result will be
+ the first item in the array that passes the truth test (iteratee) or the
+ value `undefined` if none passed.
__Example__
```js
-async.detect(['file1','file2','file3'], fs.exists, function(result){
+async.detect(['file1','file2','file3'], function(filePath, callback) {
+ fs.access(filePath, function(err) {
+ callback(null, !err)
+ });
+}, function(err, result){
// result now equals the first file in the list that exists
});
```
__Related__
-* detectSeries(arr, iterator, [callback])
-* detectLimit(arr, limit, iterator, [callback])
+* detectSeries(arr, iteratee, [callback])
+* detectLimit(arr, limit, iteratee, [callback])
---------------------------------------
-<a name="sortBy" />
-### sortBy(arr, iterator, [callback])
+<a name="sortBy"></a>
+### sortBy(arr, iteratee, [callback])
-Sorts a list by the results of running each `arr` value through an async `iterator`.
+Sorts a list by the results of running each `arr` value through an async `iteratee`.
__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
+* `iteratee(item, callback)` - A function to apply to each item in `arr`.
+ The iteratee 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`
+* `callback(err, results)` - *Optional* A callback which is called after all the `iteratee`
functions have finished, or an error occurs. Results is the items from
- the original `arr` sorted by the values returned by the `iterator` calls.
+ the original `arr` sorted by the values returned by the `iteratee` calls.
__Example__
@@ -576,95 +587,95 @@ async.sortBy([1,9,3,5], function(x, callback){
---------------------------------------
-<a name="some" />
-### some(arr, iterator, [callback])
+<a name="some"></a>
+### some(arr, iteratee, [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.
+If any iteratee 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
+* `iteratee(item, callback)` - A truth test to apply to each item in the array
+ in parallel. The iteratee 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
+* `callback(err, result)` - *Optional* A callback which is called as soon as any iteratee returns
+ `true`, or after all the iteratee 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){
+async.some(['file1','file2','file3'], function(filePath, callback) {
+ fs.access(filePath, function(err) {
+ callback(null, !err)
+ });
+}, function(err, result){
// if result is true then at least one of the files exists
});
```
__Related__
-* someLimit(arr, limit, iterator, callback)
+* someLimit(arr, limit, iteratee, callback)
---------------------------------------
-<a name="every" />
-### every(arr, iterator, [callback])
+<a name="every"></a>
+### every(arr, iteratee, [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`.
+If any iteratee call returns `false`, 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
+* `iteratee(item, callback)` - A truth test to apply to each item in the array
+ in parallel. The iteratee is passed a `callback(err, 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.**
+* `callback(err, result)` - *Optional* A callback which is called after all the `iteratee`
+ functions have finished. Result will be either `true` or `false` depending on
+ the values of the async tests.
__Example__
```js
-async.every(['file1','file2','file3'], fs.exists, function(result){
+async.every(['file1','file2','file3'], function(filePath, callback) {
+ fs.access(filePath, function(err) {
+ callback(null, !err)
+ });
+}, function(err, result){
// if result is true then every file exists
});
```
__Related__
-* everyLimit(arr, limit, iterator, callback)
+* everyLimit(arr, limit, iteratee, callback)
---------------------------------------
-<a name="concat" />
-### concat(arr, iterator, [callback])
+<a name="concat"></a>
+### concat(arr, iteratee, [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
+Applies `iteratee` to each item in `arr`, concatenating the results. Returns the
+concatenated list. The `iteratee`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.
+be returned in the original order of `arr` passed to the `iteratee` 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
+* `iteratee(item, callback)` - A function to apply to each item in `arr`.
+ The iteratee 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`
+* `callback(err, results)` - *Optional* A callback which is called after all the `iteratee`
functions have finished, or an error occurs. Results is an array containing
- the concatenated results of the `iterator` function.
+ the concatenated results of the `iteratee` function.
__Example__
@@ -676,12 +687,12 @@ async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
__Related__
-* concatSeries(arr, iterator, [callback])
+* concatSeries(arr, iteratee, [callback])
## Control Flow
-<a name="series" />
+<a name="series"></a>
### series(tasks, [callback])
Run the functions in the `tasks` array in series, each one running once the previous
@@ -751,7 +762,7 @@ function(err, results) {
---------------------------------------
-<a name="parallel" />
+<a name="parallel"></a>
### parallel(tasks, [callback])
Run the `tasks` array of functions in parallel, without waiting until the previous
@@ -823,7 +834,7 @@ __Related__
---------------------------------------
-<a name="whilst" />
+<a name="whilst"></a>
### whilst(test, fn, callback)
Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
@@ -860,7 +871,7 @@ async.whilst(
---------------------------------------
-<a name="doWhilst" />
+<a name="doWhilst"></a>
### doWhilst(fn, test, callback)
The post-check version of [`whilst`](#whilst). To reflect the difference in
@@ -870,7 +881,7 @@ the order of operations, the arguments `test` and `fn` are switched.
---------------------------------------
-<a name="until" />
+<a name="until"></a>
### until(test, fn, callback)
Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
@@ -881,14 +892,14 @@ The inverse of [`whilst`](#whilst).
---------------------------------------
-<a name="doUntil" />
+<a name="doUntil"></a>
### doUntil(fn, test, callback)
Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
---------------------------------------
-<a name="during" />
+<a name="during"></a>
### 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.
@@ -914,7 +925,7 @@ async.during(
---------------------------------------
-<a name="doDuring" />
+<a name="doDuring"></a>
### doDuring(fn, test, callback)
The post-check version of [`during`](#during). To reflect the difference in
@@ -924,7 +935,7 @@ Also a version of [`doWhilst`](#doWhilst) with asynchronous `test` function.
---------------------------------------
-<a name="forever" />
+<a name="forever"></a>
### forever(fn, [errback])
Calls the asynchronous function `fn` with a callback parameter that allows it to
@@ -948,7 +959,7 @@ async.forever(
---------------------------------------
-<a name="waterfall" />
+<a name="waterfall"></a>
### waterfall(tasks, [callback])
Runs the `tasks` array of functions in series, each passing their results to the next in
@@ -986,9 +997,56 @@ async.waterfall([
// result now equals 'done'
});
```
+Or, with named functions:
+
+```js
+async.waterfall([
+ myFirstFunction,
+ mySecondFunction,
+ myLastFunction,
+], function (err, result) {
+ // result now equals 'done'
+});
+function myFirstFunction(callback) {
+ callback(null, 'one', 'two');
+}
+function mySecondFunction(arg1, arg2, callback) {
+ // arg1 now equals 'one' and arg2 now equals 'two'
+ callback(null, 'three');
+}
+function myLastFunction(arg1, callback) {
+ // arg1 now equals 'three'
+ callback(null, 'done');
+}
+```
+
+Or, if you need to pass any argument to the first function:
+
+```js
+async.waterfall([
+ async.apply(myFirstFunction, 'zero'),
+ mySecondFunction,
+ myLastFunction,
+], function (err, result) {
+ // result now equals 'done'
+});
+function myFirstFunction(arg1, callback) {
+ // arg1 now equals 'zero'
+ callback(null, 'one', 'two');
+}
+function mySecondFunction(arg1, arg2, callback) {
+ // arg1 now equals 'one' and arg2 now equals 'two'
+ callback(null, 'three');
+}
+function myLastFunction(arg1, callback) {
+ // arg1 now equals 'three'
+ callback(null, 'done');
+}
+```
---------------------------------------
-<a name="compose" />
+
+<a name="compose"></a>
### compose(fn1, fn2...)
Creates a function which is a composition of the passed asynchronous
@@ -1026,7 +1084,8 @@ add1mul3(4, function (err, result) {
```
---------------------------------------
-<a name="seq" />
+
+<a name="seq"></a>
### seq(fn1, fn2...)
Version of the compose function that is more natural to read.
@@ -1048,25 +1107,26 @@ __Example__
// 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 });
- }
- });
+ 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" />
+
+<a name="applyEach"></a>
### applyEach(fns, args..., callback)
Applies the provided arguments to each function in the array, calling
@@ -1101,7 +1161,7 @@ __Related__
---------------------------------------
-<a name="queue" />
+<a name="queue"></a>
### queue(worker, [concurrency])
Creates a `queue` object with the specified `concurrency`. Tasks added to the
@@ -1134,8 +1194,9 @@ methods:
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.
+* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, and further tasks will be queued.
+* `unsaturated` - a callback that is called when the `queue` length is less than the `concurrency` & `buffer` limits, and further tasks will not be queued.
+* `buffer` A minimum threshold buffer in order to say that the `queue` is `unsaturated`.
* `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
@@ -1181,10 +1242,9 @@ q.unshift({name: 'bar'}, function (err) {
});
```
-
---------------------------------------
-<a name="priorityQueue" />
+<a name="priorityQueue"></a>
### 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:
@@ -1195,7 +1255,7 @@ The same as [`queue`](#queue) only tasks are assigned a priority and completed i
---------------------------------------
-<a name="cargo" />
+<a name="cargo"></a>
### cargo(worker, [payload])
Creates a `cargo` object with the specified payload. Tasks added to the
@@ -1261,60 +1321,35 @@ cargo.push({name: 'baz'}, function (err) {
---------------------------------------
-<a name="auto" />
+<a name="auto"></a>
### 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.
+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.
-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.
+Functions also receive an object containing the results of functions which have completed so far as the first argument, if they have dependencies. If a task function has no dependencies, it will only be passed a callback.
-For example, this snippet of code:
```js
async.auto({
+ // this function will just be passed a callback
readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
+ showData: ['readData', function (results, cb) {
+ // results.readData is the file's contents
+ // ...
+ }]
}, 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.
+* `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 one or two arguments:
+ * a `results` object, containing the results of the previously executed functions, only passed if the task has any dependencies,
+ * a `callback(err, result)` function, which must be called when finished, passing an `error` (which can be `null`) and the result of the function's execution.
* `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.
-
+* `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__
@@ -1331,13 +1366,13 @@ async.auto({
// this is run at the same time as getting the data
callback(null, 'folder');
},
- write_file: ['get_data', 'make_folder', function(callback, results){
+ write_file: ['get_data', 'make_folder', function(results, 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
callback(null, 'filename');
}],
- email_link: ['write_file', function(callback, results){
+ email_link: ['write_file', function(results, callback){
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.
@@ -1349,8 +1384,7 @@ async.auto({
});
```
-This is a fairly trivial example, but to do this using the basic parallel and
-series functions would look like this:
+This is a fairly trivial example, but to do this using the basic parallel and series functions would look like this:
```js
async.parallel([
@@ -1384,13 +1418,11 @@ function(err, results){
});
```
-For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
-new tasks much easier (and the code more readable).
-
+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="autoInject" />
+<a name="autoInject"></a>
### autoInject(tasks, [callback])
A dependency-injected version of the [`auto`](#auto) function. Dependent tasks are
@@ -1415,7 +1447,7 @@ __Arguments__
The remaining parameters name other tasks on which the task is dependent, and the results
from those tasks are the arguments of those parameters.
* `callback(err, [results...])` - An optional callback which is called when all the
- tasks have been completed. It receives the `err` argument if any `tasks`
+ tasks have been completed. It receives the `err` argument if any `tasks`
pass an error to their callback. The remaining parameters are task names whose results
you are interested in. This callback will only be called when all tasks have finished or
an error has occurred, and so do not not specify dependencies in the same way as `tasks`
@@ -1457,7 +1489,7 @@ async.autoInject({
---------------------------------------
-<a name="retry" />
+<a name="retry"></a>
### retry([opts = {times: 5, interval: 0}| 5], task, [callback])
Attempts to get a successful response from `task` no more than `times` times before
@@ -1467,8 +1499,10 @@ 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).
+* `opts` - Can be either an object with `times` and `interval` or a number.
+ * `times` - The number of attempts to make before giving up. The default is `5`.
+ * `interval` - The time to wait between retries, in milliseconds. The default is `0`.
+ * If `opts` is a number, the number specifies the number of times to retry, with the default interval of `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
@@ -1476,21 +1510,29 @@ __Arguments__
* `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:
+The [`retry`](#retry) function can be used as a stand-alone control flow by passing a callback, as shown below:
```js
+// try calling apiMethod 3 times
async.retry(3, apiMethod, function(err, result) {
// do something with the result
});
```
```js
+// try calling apiMethod 3 times, waiting 200 ms between each retry
async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
// do something with the result
});
```
+```js
+// try calling apiMethod the default 5 times no delay between each retry
+async.retry(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:
@@ -1503,10 +1545,9 @@ async.auto({
});
```
-
---------------------------------------
-<a name="iterator" />
+<a name="iterator"></a>
### iterator(tasks)
Creates an iterator function which calls the next function in the `tasks` array,
@@ -1540,9 +1581,9 @@ node> nextfn();
'three'
```
----------------------------------------
+## Utils
-<a name="apply" />
+<a name="apply"></a>
### apply(function, arguments..)
Creates a continuation function with some arguments already applied.
@@ -1593,7 +1634,7 @@ three
---------------------------------------
-<a name="nextTick" />
+<a name="nextTick"></a>
### nextTick(callback), setImmediate(callback)
Calls `callback` on a later loop around the event loop. In Node.js this just
@@ -1618,16 +1659,18 @@ async.nextTick(function(){
call_order.push('one')
```
-<a name="times" />
-### times(n, iterator, [callback])
+---------------------------------------
-Calls the `iterator` function `n` times, and accumulates results in the same manner
+<a name="times"></a>
+### times(n, iteratee, [callback])
+
+Calls the `iteratee` 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.
+* `iteratee` - The function to call `n` times.
* `callback` - see [`map`](#map)
__Example__
@@ -1651,13 +1694,52 @@ async.times(5, function(n, next){
__Related__
-* timesSeries(n, iterator, [callback])
-* timesLimit(n, limit, iterator, [callback])
+* timesSeries(n, iteratee, [callback])
+* timesLimit(n, limit, iteratee, [callback])
+---------------------------------------
-## Utils
+<a name="race" />
+### race(tasks, [callback])
+
+Runs the `tasks` array of functions in parallel, without waiting until the
+previous function has completed. Once any the `tasks` completed or pass an
+error to its callback, the main `callback` is immediately called. It's
+equivalent to `Promise.race()`.
+
+__Arguments__
+
+* `tasks` - An array 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, result)` - A callback to run once any of the
+ functions have completed. This function gets an error or result from the
+ first function that completed.
-<a name="memoize" />
+__Example__
+
+```js
+async.race([
+ function(callback){
+ setTimeout(function(){
+ callback(null, 'one');
+ }, 200);
+ },
+ function(callback){
+ setTimeout(function(){
+ callback(null, 'two');
+ }, 100);
+ }
+],
+// main callback
+function(err, result){
+ // the result will be equal to 'two' as it finishes earlier
+});
+```
+
+---------------------------------------
+
+<a name="memoize"></a>
### memoize(fn, [hasher])
Caches the results of an `async` function. When creating a hash to store function
@@ -1691,7 +1773,9 @@ fn('some name', function () {
});
```
-<a name="unmemoize" />
+---------------------------------------
+
+<a name="unmemoize"></a>
### unmemoize(fn)
Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
@@ -1703,7 +1787,7 @@ __Arguments__
---------------------------------------
-<a name="ensureAsync" />
+<a name="ensureAsync"></a>
### 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.
@@ -1718,11 +1802,11 @@ __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
- }
+ 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
@@ -1736,7 +1820,7 @@ async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
---------------------------------------
-<a name="constant">
+<a name="constant"></a>
### 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`.
@@ -1745,37 +1829,37 @@ __Example__
```js
async.waterfall([
- async.constant(42),
- function (value, next) {
- // value === 42
- },
- //...
+ async.constant(42),
+ function (value, next) {
+ // value === 42
+ },
+ //...
], callback);
async.waterfall([
- async.constant(filename, "utf8"),
- fs.readFile,
- function (fileData, next) {
+ 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);
- }],
- //...
+ hostname: async.constant("https://server.net/"),
+ port: findFreePort,
+ launchServer: ["hostname", "port", function (options, cb) {
+ startServer(options, cb);
+ }],
+ //...
}, callback);
```
---------------------------------------
-<a name="asyncify">
-<a name="wrapSync">
+<a name="asyncify"></a>
+<a name="wrapSync"></a>
### asyncify(func)
__Alias:__ `wrapSync`
@@ -1786,18 +1870,44 @@ __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.
- }
+ 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)
+```
+
+If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value. Example:
+
+```js
+async.waterfall([
+ async.apply(fs.readFile, filename, "utf8"),
+ async.asyncify(function (contents) {
+ return db.model.create(contents);
+ }),
+ function (model, next) {
+ // `model` is the instantiated model object.
+ // If there was an error, this function would be skipped.
+ }
], callback)
```
+This also means you can asyncify ES2016 `async` functions.
+
+```js
+var q = async.queue(async.asyncify(async function (file) {
+ var intermediateStep = await processFile(file);
+ return await somePromise(intermediateStep)
+}));
+
+q.push(files);
+```
+
---------------------------------------
-<a name="log" />
+<a name="log"></a>
### log(function, arguments)
Logs the result of an `async` function to the `console`. Only works in Node.js or
@@ -1826,7 +1936,7 @@ node> async.log(hello, 'world');
---------------------------------------
-<a name="dir" />
+<a name="dir"></a>
### dir(function, arguments)
Logs the result of an `async` function to the `console` using `console.dir` to
@@ -1856,7 +1966,7 @@ node> async.dir(hello, 'world');
---------------------------------------
-<a name="noConflict" />
+<a name="noConflict"></a>
### noConflict()
Changes the value of `async` back to its original value, returning a reference to the
diff --git a/bower.json b/bower.json
index 7a5b5e6..c708594 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": "dist/async.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,16 +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",
- "xyz": "^0.5.0",
+ "vinyl-buffer": "~1.0.0",
+ "vinyl-source-stream": "~1.1.0",
"yargs": "~3.9.1"
},
"moduleType": [
@@ -52,6 +63,5 @@
],
"authors": [
"Caolan McMahon"
- ],
- "version": "1.5.1"
-}
+ ]
+} \ No newline at end of file
diff --git a/component.json b/component.json
index a5d77f4..2ce99fc 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.1",
+ "version": "2.0.0-alpha",
"keywords": [
"async",
"callback",
- "utility",
- "module"
+ "module",
+ "utility"
],
"license": "MIT",
- "main": "lib/async.js",
+ "main": "dist/async.js",
"repository": "caolan/async",
"scripts": [
- "lib/async.js"
+ "dist/async.js"
]
-}
+} \ No newline at end of file
diff --git a/dist/async.js b/dist/async.js
index 9ecbda6..0032ce5 100644
--- a/dist/async.js
+++ b/dist/async.js
@@ -1,1264 +1,2563 @@
-/*!
- * async
- * https://github.com/caolan/async
- *
- * Copyright 2010-2014 Caolan McMahon
- * Released under the MIT license
- */
-(function () {
-
- var async = {};
- function noop() {}
- function identity(v) {
- return v;
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
+ (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.length;
+ 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]);
}
- function toBool(v) {
- return !!v;
+ 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('')`)
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
+ * @example
+ *
+ * _.isObject({});
+ * // => true
+ *
+ * _.isObject([1, 2, 3]);
+ * // => true
+ *
+ * _.isObject(_.noop);
+ * // => true
+ *
+ * _.isObject(null);
+ * // => false
+ */
+ function isObject(value) {
+ var type = typeof value;
+ return !!value && (type == 'object' || type == 'function');
+ }
+
+ var funcTag = '[object Function]';
+ var genTag = '[object GeneratorFunction]';
+ /** Used for built-in method references. */
+ var objectProto$4 = Object.prototype;
+
+ /**
+ * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+ var objectToString$2 = objectProto$4.toString;
+
+ /**
+ * Checks if `value` is classified as a `Function` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isFunction(_);
+ * // => true
+ *
+ * _.isFunction(/abc/);
+ * // => false
+ */
+ function isFunction(value) {
+ // The use of `Object#toString` avoids issues with the `typeof` operator
+ // in Safari 8 which returns 'object' for typed array constructors, and
+ // PhantomJS 1.9 which returns 'function' for `NodeList` instances.
+ var tag = isObject(value) ? objectToString$2.call(value) : '';
+ return tag == funcTag || tag == genTag;
+ }
+
+ /** Used as references for various `Number` constants. */
+ var NAN = 0 / 0;
+
+ /** Used to match leading and trailing whitespace. */
+ var reTrim = /^\s+|\s+$/g;
+
+ /** Used to detect bad signed hexadecimal string values. */
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
+
+ /** Used to detect binary string values. */
+ var reIsBinary = /^0b[01]+$/i;
+
+ /** Used to detect octal string values. */
+ var reIsOctal = /^0o[0-7]+$/i;
+
+ /** Built-in method references without a dependency on `root`. */
+ var freeParseInt = parseInt;
+
+ /**
+ * Converts `value` to a number.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to process.
+ * @returns {number} Returns the number.
+ * @example
+ *
+ * _.toNumber(3);
+ * // => 3
+ *
+ * _.toNumber(Number.MIN_VALUE);
+ * // => 5e-324
+ *
+ * _.toNumber(Infinity);
+ * // => Infinity
+ *
+ * _.toNumber('3');
+ * // => 3
+ */
+ function toNumber(value) {
+ if (isObject(value)) {
+ var other = isFunction(value.valueOf) ? value.valueOf() : value;
+ value = isObject(other) ? (other + '') : other;
}
- function notId(v) {
- return !v;
+ if (typeof value != 'string') {
+ return value === 0 ? value : +value;
}
-
- // global on the server, window in the browser
- var previous_async;
-
- // Establish the root object, `window` (`self`) in the browser, `global`
- // on the server, or `this` in some virtual machines. We use `self`
- // instead of `window` for `WebWorker` support.
- var root = typeof self === 'object' && self.self === self && self ||
- typeof global === 'object' && global.global === global && global ||
- this;
-
- if (root != null) {
- previous_async = root.async;
+ value = value.replace(reTrim, '');
+ var isBinary = reIsBinary.test(value);
+ return (isBinary || reIsOctal.test(value))
+ ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
+ : (reIsBadHex.test(value) ? NAN : +value);
+ }
+
+ var INFINITY = 1 / 0;
+ var MAX_INTEGER = 1.7976931348623157e+308;
+ /**
+ * Converts `value` to an integer.
+ *
+ * **Note:** This function is loosely based on [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {number} Returns the converted integer.
+ * @example
+ *
+ * _.toInteger(3);
+ * // => 3
+ *
+ * _.toInteger(Number.MIN_VALUE);
+ * // => 0
+ *
+ * _.toInteger(Infinity);
+ * // => 1.7976931348623157e+308
+ *
+ * _.toInteger('3');
+ * // => 3
+ */
+ function toInteger(value) {
+ if (!value) {
+ return value === 0 ? value : 0;
}
-
- async.noConflict = function () {
- root.async = previous_async;
- return async;
- };
-
- function only_once(fn) {
- return function() {
- if (fn === null) throw new Error("Callback was already called.");
- fn.apply(this, arguments);
- fn = null;
- };
+ value = toNumber(value);
+ if (value === INFINITY || value === -INFINITY) {
+ var sign = (value < 0 ? -1 : 1);
+ return sign * MAX_INTEGER;
}
-
- function _once(fn) {
- return function() {
- if (fn === null) return;
- fn.apply(this, arguments);
- fn = null;
- };
+ var remainder = value % 1;
+ return value === value ? (remainder ? value - remainder : value) : 0;
+ }
+
+ /** Used as the `TypeError` message for "Functions" methods. */
+ var FUNC_ERROR_TEXT = 'Expected a function';
+
+ /* Built-in method references for those with the same name as other `lodash` methods. */
+ var nativeMax = Math.max;
+
+ /**
+ * Creates a function that invokes `func` with the `this` binding of the
+ * created function and arguments from `start` and beyond provided as an array.
+ *
+ * **Note:** This method is based on the [rest parameter](https://mdn.io/rest_parameters).
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to apply a rest parameter to.
+ * @param {number} [start=func.length-1] The start position of the rest parameter.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var say = _.rest(function(what, names) {
+ * return what + ' ' + _.initial(names).join(', ') +
+ * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
+ * });
+ *
+ * say('hello', 'fred', 'barney', 'pebbles');
+ * // => 'hello fred, barney, & pebbles'
+ */
+ function rest(func, start) {
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
}
-
- //// cross-browser compatiblity functions ////
-
- var _toString = Object.prototype.toString;
-
- var _isArray = Array.isArray || function (obj) {
- return _toString.call(obj) === '[object Array]';
- };
-
- // Ported from underscore.js isObject
- var _isObject = function(obj) {
- var type = typeof obj;
- return type === 'function' || type === 'object' && !!obj;
+ start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0);
+ return function() {
+ var args = arguments,
+ index = -1,
+ length = nativeMax(args.length - start, 0),
+ array = Array(length);
+
+ while (++index < length) {
+ array[index] = args[start + index];
+ }
+ switch (start) {
+ case 0: return func.call(this, array);
+ case 1: return func.call(this, args[0], array);
+ case 2: return func.call(this, args[0], args[1], array);
+ }
+ var otherArgs = Array(start + 1);
+ index = -1;
+ while (++index < start) {
+ otherArgs[index] = args[index];
+ }
+ otherArgs[start] = array;
+ return apply$1(func, this, otherArgs);
};
-
- function _isArrayLike(arr) {
- return _isArray(arr) || (
- // has a positive integer length property
- typeof arr.length === "number" &&
- arr.length >= 0 &&
- arr.length % 1 === 0
- );
+ }
+
+ 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 {
+ return go;
+ }
+ });
+ }
+
+ /** Used as the `TypeError` message for "Functions" methods. */
+ var FUNC_ERROR_TEXT$1 = 'Expected a function';
+
+ /**
+ * Creates a function that invokes `func`, with the `this` binding and arguments
+ * of the created function, while it's called less than `n` times. Subsequent
+ * calls to the created function return the result of the last `func` invocation.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {number} n The number of calls at which `func` is no longer invoked.
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * jQuery(element).on('click', _.before(5, addContactToList));
+ * // => allows adding up to 4 contacts to the list
+ */
+ function before(n, func) {
+ var result;
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT$1);
}
-
- function _arrayEach(arr, iterator) {
- var index = -1,
- length = arr.length;
-
- while (++index < length) {
- iterator(arr[index], index, arr);
- }
+ n = toInteger(n);
+ return function() {
+ if (--n > 0) {
+ result = func.apply(this, arguments);
+ }
+ if (n <= 1) {
+ func = undefined;
+ }
+ return result;
+ };
+ }
+
+ /**
+ * Creates a function that is restricted to invoking `func` once. Repeat calls
+ * to the function return the value of the first invocation. The `func` is
+ * invoked with the `this` binding and arguments of the created function.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * var initialize = _.once(createApplication);
+ * initialize();
+ * initialize();
+ * // `initialize` invokes `createApplication` once
+ */
+ function once(func) {
+ return before(2, func);
+ }
+
+ /**
+ * A no-operation function that returns `undefined` regardless of the
+ * arguments it receives.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @example
+ *
+ * var object = { 'user': 'fred' };
+ *
+ * _.noop(object) === undefined;
+ * // => true
+ */
+ function noop() {
+ // No operation performed.
+ }
+
+ /**
+ * 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)
+ * that affects Safari on at least iOS 8.1-8.3 ARM64.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {*} Returns the "length" value.
+ */
+ var getLength = baseProperty('length');
+
+ /** Used as references for various `Number` constants. */
+ var MAX_SAFE_INTEGER$1 = 9007199254740991;
+
+ /**
+ * Checks if `value` is a valid array-like length.
+ *
+ * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
+ * @example
+ *
+ * _.isLength(3);
+ * // => true
+ *
+ * _.isLength(Number.MIN_VALUE);
+ * // => false
+ *
+ * _.isLength(Infinity);
+ * // => false
+ *
+ * _.isLength('3');
+ * // => false
+ */
+ function isLength(value) {
+ return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
+ }
+
+ /**
+ * Checks if `value` is array-like. A value is considered array-like if it's
+ * not a function and has a `value.length` that's an integer greater than or
+ * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
+ *
+ * @static
+ * @memberOf _
+ * @type Function
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
+ * @example
+ *
+ * _.isArrayLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isArrayLike(document.body.children);
+ * // => true
+ *
+ * _.isArrayLike('abc');
+ * // => true
+ *
+ * _.isArrayLike(_.noop);
+ * // => false
+ */
+ function isArrayLike(value) {
+ return value != null &&
+ !(typeof value == 'function' && isFunction(value)) && isLength(getLength(value));
+ }
+
+ /** Used for built-in method references. */
+ var objectProto = Object.prototype;
+
+ /** Used to check objects for own properties. */
+ var hasOwnProperty = objectProto.hasOwnProperty;
+
+ /** Built-in value references. */
+ var getPrototypeOf = Object.getPrototypeOf;
+
+ /**
+ * The base implementation of `_.has` without support for deep paths.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} key The key to check.
+ * @returns {boolean} Returns `true` if `key` exists, else `false`.
+ */
+ function baseHas(object, key) {
+ // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
+ // that are composed entirely of index properties, return `false` for
+ // `hasOwnProperty` checks of them.
+ return hasOwnProperty.call(object, key) ||
+ (typeof object == 'object' && key in object && getPrototypeOf(object) === null);
+ }
+
+ /* Built-in method references for those with the same name as other `lodash` methods. */
+ var nativeKeys = Object.keys;
+
+ /**
+ * The base implementation of `_.keys` which doesn't skip the constructor
+ * property of prototypes or treat sparse arrays as dense.
+ *
+ * @private
+ * @type Function
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
+ function baseKeys(object) {
+ return nativeKeys(Object(object));
+ }
+
+ /**
+ * The base implementation of `_.times` without support for iteratee shorthands
+ * or max array length checks.
+ *
+ * @private
+ * @param {number} n The number of times to invoke `iteratee`.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the array of results.
+ */
+ function baseTimes(n, iteratee) {
+ var index = -1,
+ result = Array(n);
+
+ while (++index < n) {
+ result[index] = iteratee(index);
}
-
- function _map(arr, iterator) {
- var index = -1,
- length = arr.length,
- result = Array(length);
-
- while (++index < length) {
- result[index] = iterator(arr[index], index, arr);
- }
- return result;
+ return result;
+ }
+
+ /**
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
+ * and has a `typeof` result of "object".
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
+ * @example
+ *
+ * _.isObjectLike({});
+ * // => true
+ *
+ * _.isObjectLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isObjectLike(_.noop);
+ * // => false
+ *
+ * _.isObjectLike(null);
+ * // => false
+ */
+ function isObjectLike(value) {
+ return !!value && typeof value == 'object';
+ }
+
+ /**
+ * This method is like `_.isArrayLike` except that it also checks if `value`
+ * is an object.
+ *
+ * @static
+ * @memberOf _
+ * @type Function
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`.
+ * @example
+ *
+ * _.isArrayLikeObject([1, 2, 3]);
+ * // => true
+ *
+ * _.isArrayLikeObject(document.body.children);
+ * // => true
+ *
+ * _.isArrayLikeObject('abc');
+ * // => false
+ *
+ * _.isArrayLikeObject(_.noop);
+ * // => false
+ */
+ function isArrayLikeObject(value) {
+ return isObjectLike(value) && isArrayLike(value);
+ }
+
+ /** `Object#toString` result references. */
+ var argsTag = '[object Arguments]';
+
+ /** Used for built-in method references. */
+ var objectProto$2 = Object.prototype;
+
+ /** Used to check objects for own properties. */
+ var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
+
+ /**
+ * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+ var objectToString = objectProto$2.toString;
+
+ /** Built-in value references. */
+ var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
+
+ /**
+ * Checks if `value` is likely an `arguments` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isArguments(function() { return arguments; }());
+ * // => true
+ *
+ * _.isArguments([1, 2, 3]);
+ * // => false
+ */
+ function isArguments(value) {
+ // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
+ return isArrayLikeObject(value) && hasOwnProperty$1.call(value, 'callee') &&
+ (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
+ }
+
+ /**
+ * Checks if `value` is classified as an `Array` object.
+ *
+ * @static
+ * @memberOf _
+ * @type Function
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isArray([1, 2, 3]);
+ * // => true
+ *
+ * _.isArray(document.body.children);
+ * // => false
+ *
+ * _.isArray('abc');
+ * // => false
+ *
+ * _.isArray(_.noop);
+ * // => false
+ */
+ var isArray = Array.isArray;
+
+ /** `Object#toString` result references. */
+ var stringTag = '[object String]';
+
+ /** Used for built-in method references. */
+ var objectProto$3 = Object.prototype;
+
+ /**
+ * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+ var objectToString$1 = objectProto$3.toString;
+
+ /**
+ * Checks if `value` is classified as a `String` primitive or object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isString('abc');
+ * // => true
+ *
+ * _.isString(1);
+ * // => false
+ */
+ function isString(value) {
+ return typeof value == 'string' ||
+ (!isArray(value) && isObjectLike(value) && objectToString$1.call(value) == stringTag);
+ }
+
+ /**
+ * Creates an array of index keys for `object` values of arrays,
+ * `arguments` objects, and strings, otherwise `null` is returned.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array|null} Returns index keys, else `null`.
+ */
+ function indexKeys(object) {
+ var length = object ? object.length : undefined;
+ if (isLength(length) &&
+ (isArray(object) || isString(object) || isArguments(object))) {
+ return baseTimes(length, String);
}
-
- function _range(count) {
- return _map(Array(count), function (v, i) { return i; });
+ return null;
+ }
+
+ /** Used as references for various `Number` constants. */
+ var MAX_SAFE_INTEGER = 9007199254740991;
+
+ /** Used to detect unsigned integer values. */
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
+
+ /**
+ * Checks if `value` is a valid array-like index.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
+ * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
+ */
+ function isIndex(value, length) {
+ value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
+ length = length == null ? MAX_SAFE_INTEGER : length;
+ return value > -1 && value % 1 == 0 && value < length;
+ }
+
+ /** Used for built-in method references. */
+ var objectProto$1 = Object.prototype;
+
+ /**
+ * Checks if `value` is likely a prototype object.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
+ */
+ function isPrototype(value) {
+ var Ctor = value && value.constructor,
+ proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$1;
+
+ return value === proto;
+ }
+
+ /**
+ * Creates an array of the own enumerable property names of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects. See the
+ * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
+ * for more details.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.keys(new Foo);
+ * // => ['a', 'b'] (iteration order is not guaranteed)
+ *
+ * _.keys('hi');
+ * // => ['0', '1']
+ */
+ function keys(object) {
+ var isProto = isPrototype(object);
+ if (!(isProto || isArrayLike(object))) {
+ return baseKeys(object);
}
-
- function _reduce(arr, iterator, memo) {
- _arrayEach(arr, function (x, i, a) {
- memo = iterator(memo, x, i, a);
- });
- return memo;
+ var indexes = indexKeys(object),
+ skipIndexes = !!indexes,
+ result = indexes || [],
+ length = result.length;
+
+ for (var key in object) {
+ if (baseHas(object, key) &&
+ !(skipIndexes && (key == 'length' || isIndex(key, length))) &&
+ !(isProto && key == 'constructor')) {
+ result.push(key);
+ }
}
-
- function _forEachOf(object, iterator) {
- _arrayEach(_keys(object), function (key) {
- iterator(object[key], key);
- });
+ return result;
+ }
+
+ 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;
+ };
+ }
+ }
+
+ function onlyOnce(fn) {
+ return function () {
+ if (fn === null) throw new Error("Callback was already called.");
+ fn.apply(this, arguments);
+ fn = null;
+ };
+ }
+
+ 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;
+ 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);
+ };
+ }
+
+ var setImmediate$1 = _delay;
+
+ 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$1(iterate);
+ } else {
+ iterate();
+ }
+ }
+ }
+ }));
+ sync = false;
+ }
+ iterate();
+ }
+
+ var applyEachSeries = applyEach$1(eachOfSeries);
+
+ var apply = rest(function (fn, args) {
+ return rest(function (callArgs) {
+ return fn.apply(null, args.concat(callArgs));
+ });
+ });
+
+ 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);
+ }
+ });
+ }
+
+ /**
+ * 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;
+
+ while (++index < length) {
+ if (iteratee(array[index], index, array) === false) {
+ break;
+ }
}
-
- function _indexOf(arr, item) {
- for (var i = 0; i < arr.length; i++) {
- if (arr[i] === item) return i;
- }
- return -1;
+ return array;
+ }
+
+ /**
+ * 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;
+
+ while (++index < length) {
+ if (!predicate(array[index], index, array)) {
+ return false;
+ }
}
-
- var _keys = Object.keys || function (obj) {
- var keys = [];
- for (var k in obj) {
- if (obj.hasOwnProperty(k)) {
- keys.push(k);
- }
+ return true;
+ }
+
+ /**
+ * 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;
+
+ while (length--) {
+ var key = props[fromRight ? length : ++index];
+ if (iteratee(iterable[key], key, iterable) === false) {
+ break;
}
- return keys;
+ }
+ return object;
};
-
- function _keyIterator(coll) {
- var i = -1;
- var len;
- var keys;
- if (_isArrayLike(coll)) {
- len = coll.length;
- return function next() {
- i++;
- return i < len ? i : null;
- };
- } else {
- keys = _keys(coll);
- len = keys.length;
- return function next() {
- i++;
- return i < len ? keys[i] : null;
- };
- }
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * This method returns the first argument given to it.
+ *
+ * @static
+ * @memberOf _
+ * @category Util
+ * @param {*} value Any value.
+ * @returns {*} Returns `value`.
+ * @example
+ *
+ * var object = { 'user': 'fred' };
+ *
+ * _.identity(object) === object;
+ * // => true
+ */
+ function identity(value) {
+ return value;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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);
+
+ while ((fromRight ? index-- : ++index < length)) {
+ var other = array[index];
+ if (other !== other) {
+ return index;
+ }
}
-
- // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
- // This accumulates the arguments passed into an array, after a given index.
- // From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
- function _restParam(func, startIndex) {
- startIndex = startIndex == null ? func.length - 1 : +startIndex;
- return function() {
- var length = Math.max(arguments.length - startIndex, 0);
- var rest = Array(length);
- for (var index = 0; index < length; index++) {
- rest[index] = arguments[index + startIndex];
- }
- switch (startIndex) {
- case 0: return func.call(this, rest);
- case 1: return func.call(this, arguments[0], rest);
- }
- // Currently unused but handle cases outside of the switch statement:
- // var args = Array(startIndex + 1);
- // for (index = 0; index < startIndex; index++) {
- // args[index] = arguments[index];
- // }
- // args[startIndex] = rest;
- // return func.apply(this, args);
- };
+ 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 _withoutIndex(iterator) {
- return function (value, index, callback) {
- return iterator(value, callback);
- };
+ while (++index < length) {
+ if (array[index] === value) {
+ return index;
+ }
}
-
- //// exported async module functions ////
-
- //// nextTick implementation with browser-compatible fallback ////
-
- // capture the global reference to guard against fakeTimer mocks
- var _setImmediate = typeof setImmediate === 'function' && setImmediate;
-
- var _delay = _setImmediate ? function(fn) {
- // not a direct alias for IE10 compatibility
- _setImmediate(fn);
- } : function(fn) {
- setTimeout(fn, 0);
- };
-
- if (typeof process === 'object' && typeof process.nextTick === 'function') {
- async.nextTick = process.nextTick;
- } else {
- async.nextTick = _delay;
+ return -1;
+ }
+
+ /* Built-in method references for those with the same name as other `lodash` methods. */
+ var nativeMax$1 = Math.max;
+
+ /**
+ * 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`.
+ *
+ * @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
+ *
+ * // Search from the `fromIndex`.
+ * _.indexOf([1, 2, 1, 2], 2, 2);
+ * // => 3
+ */
+ function indexOf(array, value, fromIndex) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return -1;
}
- async.setImmediate = _setImmediate ? _delay : async.nextTick;
-
-
- async.forEach =
- async.each = function (arr, iterator, callback) {
- return async.eachOf(arr, _withoutIndex(iterator), callback);
- };
-
- async.forEachSeries =
- async.eachSeries = function (arr, iterator, callback) {
- return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
- };
-
-
- async.forEachLimit =
- async.eachLimit = function (arr, limit, iterator, callback) {
- return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
- };
-
- async.forEachOf =
- async.eachOf = function (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, only_once(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);
- }
- }
- };
-
- async.forEachOfSeries =
- async.eachOfSeries = function (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, only_once(function (err) {
- if (err) {
- callback(err);
- }
- else {
- key = nextKey();
- if (key === null) {
- return callback(null);
- } else {
- if (sync) {
- async.setImmediate(iterate);
- } else {
- iterate();
- }
- }
- }
- }));
- sync = false;
- }
- iterate();
- };
-
-
-
- async.forEachOfLimit =
- async.eachOfLimit = function (obj, limit, iterator, callback) {
- _eachOfLimit(limit)(obj, iterator, callback);
- };
-
- 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, only_once(function (err) {
- running -= 1;
- if (err) {
- callback(err);
- errored = true;
- }
- else {
- replenish();
- }
- }));
- }
- })();
- };
- }
-
-
- function doParallel(fn) {
- return function (obj, iterator, callback) {
- return fn(async.eachOf, obj, iterator, callback);
- };
+ fromIndex = toInteger(fromIndex);
+ if (fromIndex < 0) {
+ fromIndex = nativeMax$1(length + fromIndex, 0);
}
- function doParallelLimit(fn) {
- return function (obj, limit, iterator, callback) {
- return fn(_eachOfLimit(limit), obj, iterator, callback);
- };
+ return baseIndexOf(array, value, fromIndex);
+ }
+
+ 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;
+ }
+
+ var results = {};
+ var runningTasks = 0;
+ var hasError = false;
+
+ 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) {
+ if (hasError) return;
+ 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;
+ hasError = true;
+
+ 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 non-existent dependency in ' + requires.join(', '));
+ }
+ 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);
+ }
+ }
+ });
+ }
+
+ /**
+ * 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);
}
- function doSeries(fn) {
- return function (obj, iterator, callback) {
- return fn(async.eachOfSeries, obj, iterator, callback);
- };
+ return result;
+ }
+
+ function queue$1(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$1(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$1(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, baseProperty('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$1(q.process);
+ }
+ }
+ };
+ return q;
+ }
+
+ function cargo(worker, payload) {
+ return queue$1(worker, 1, payload);
+ }
+
+ 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 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));
+ });
+ });
+ }
+
+ var reverse = Array.prototype.reverse;
+
+ function compose() /* functions... */{
+ return seq.apply(null, reverse.call(arguments));
+ }
+
+ 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 doParallel(fn) {
+ return function (obj, iterator, callback) {
+ return fn(eachOf, obj, iterator, callback);
+ };
+ }
+
+ var concat = doParallel(concat$1);
+
+ function doSeries(fn) {
+ return function (obj, iterator, callback) {
+ return fn(eachOfSeries, obj, iterator, callback);
+ };
+ }
+
+ var concatSeries = doSeries(concat$1);
+
+ 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(err) {
+ if (cb) {
+ if (err) {
+ cb(err);
+ } else {
+ cb(null, getResult(false, void 0));
+ }
+ }
+ }
+ function iteratee(x, _, callback) {
+ if (!cb) return callback();
+ iterator(x, function (err, v) {
+ if (cb) {
+ if (err) {
+ cb(err);
+ cb = iterator = false;
+ } else if (check(v)) {
+ cb(null, 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);
+ }
+ };
+ }
+
+ 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) {
+ if (typeof console === 'object') {
+ if (err) {
+ if (console.error) {
+ console.error(err);
+ }
+ } else if (console[name]) {
+ arrayEach(args, function (x) {
+ console[name](x);
+ });
+ }
+ }
+ })]));
+ });
+ }
+
+ var dir = consoleFunc('dir');
+
+ 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);
+ }
+
+ 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 () {
+ return ++calls <= 1 || test.apply(this, arguments);
+ }, iterator, cb);
+ }
+
+ function doUntil(iterator, test, cb) {
+ return doWhilst(iterator, function () {
+ return !test.apply(this, arguments);
+ }, cb);
+ }
+
+ function _withoutIndex(iterator) {
+ return function (value, index, callback) {
+ return iterator(value, callback);
+ };
+ }
+
+ function each(arr, iterator, cb) {
+ return eachOf(arr, _withoutIndex(iterator), cb);
+ }
+
+ function eachLimit(arr, limit, iterator, cb) {
+ return _eachOfLimit(limit)(arr, _withoutIndex(iterator), cb);
+ }
+
+ function eachSeries(arr, iterator, cb) {
+ return eachOfSeries(arr, _withoutIndex(iterator), cb);
+ }
+
+ 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 notId(v) {
+ return !v;
+ }
+
+ var every = _createTester(eachOf, notId, notId);
+
+ var everyLimit = _createTester(eachOfLimit, notId, notId);
+
+ function _filter(eachfn, arr, iterator, callback) {
+ var results = [];
+ eachfn(arr, function (x, index, callback) {
+ iterator(x, function (err, v) {
+ if (err) {
+ callback(err);
+ } else {
+ if (v) {
+ results.push({ index: index, value: x });
+ }
+ callback();
+ }
+ });
+ }, function (err) {
+ if (err) {
+ callback(err);
+ } else {
+ callback(null, arrayMap(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), baseProperty('value')));
+ }
+ });
+ }
+
+ var filter = doParallel(_filter);
+
+ function doParallelLimit(fn) {
+ return function (obj, limit, iterator, callback) {
+ return fn(_eachOfLimit(limit), obj, iterator, callback);
+ };
+ }
+
+ var filterLimit = doParallelLimit(_filter);
+
+ 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 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);
+ }
+
+ var log = consoleFunc('log');
+
+ 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);
+ });
+ }
+
+ var map = doParallel(_asyncMap);
+
+ var mapLimit = doParallelLimit(_asyncMap);
+
+ var mapSeries = doSeries(_asyncMap);
+
+ /**
+ * Checks if `value` is a global object.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {null|Object} Returns `value` if it's a global object, else `null`.
+ */
+ function checkGlobal(value) {
+ return (value && value.Object === Object) ? value : null;
+ }
+
+ /** Used to determine if values are of the language type `Object`. */
+ var objectTypes = {
+ 'function': true,
+ 'object': true
+ };
+
+ /** Detect free variable `exports`. */
+ var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
+
+ /** Detect free variable `module`. */
+ var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
+
+ /** Detect free variable `global` from Node.js. */
+ var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
+
+ /** Detect free variable `self`. */
+ var freeSelf = checkGlobal(objectTypes[typeof self] && self);
+
+ /** Detect free variable `window`. */
+ var freeWindow = checkGlobal(objectTypes[typeof window] && window);
+
+ /** Detect `this` as the global object. */
+ var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
+
+ /**
+ * Used as a reference to the global object.
+ *
+ * The `this` value is used if it's the global object to avoid Greasemonkey's
+ * restricted `window` object, otherwise the `window` object is used.
+ */
+ var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
+
+ /** Built-in value references. */
+ var Symbol = root.Symbol;
+
+ /** `Object#toString` result references. */
+ var symbolTag = '[object Symbol]';
+
+ /** Used for built-in method references. */
+ var objectProto$5 = Object.prototype;
+
+ /**
+ * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+ var objectToString$3 = objectProto$5.toString;
+
+ /**
+ * Checks if `value` is classified as a `Symbol` primitive or object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isSymbol(Symbol.iterator);
+ * // => true
+ *
+ * _.isSymbol('abc');
+ * // => false
+ */
+ function isSymbol(value) {
+ return typeof value == 'symbol' ||
+ (isObjectLike(value) && objectToString$3.call(value) == symbolTag);
+ }
+
+ /** Used as references for various `Number` constants. */
+ var INFINITY$1 = 1 / 0;
+
+ /** Used to convert symbols to primitives and strings. */
+ var symbolProto = Symbol ? Symbol.prototype : undefined;
+ var symbolToString = Symbol ? symbolProto.toString : undefined;
+ /**
+ * Converts `value` to a string if it's not one. An empty string is returned
+ * for `null` and `undefined` values. The sign of `-0` is preserved.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to process.
+ * @returns {string} Returns the string.
+ * @example
+ *
+ * _.toString(null);
+ * // => ''
+ *
+ * _.toString(-0);
+ * // => '-0'
+ *
+ * _.toString([1, 2, 3]);
+ * // => '1,2,3'
+ */
+ function toString(value) {
+ // Exit early for strings to avoid a performance hit in some environments.
+ if (typeof value == 'string') {
+ return value;
}
-
- 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);
- });
+ if (value == null) {
+ return '';
}
-
- async.map = doParallel(_asyncMap);
- async.mapSeries = doSeries(_asyncMap);
- async.mapLimit = doParallelLimit(_asyncMap);
-
- // reduce only has a series version, as doing reduce in parallel won't
- // work in many situations.
- async.inject =
- async.foldl =
- async.reduce = function (arr, memo, iterator, callback) {
- async.eachOfSeries(arr, function (x, i, callback) {
- iterator(memo, x, function (err, v) {
- memo = v;
- callback(err);
- });
- }, function (err) {
- callback(err, memo);
- });
- };
-
- async.foldr =
- async.reduceRight = function (arr, memo, iterator, callback) {
- var reversed = _map(arr, identity).reverse();
- async.reduce(reversed, memo, iterator, callback);
- };
-
- async.transform = function (arr, memo, iterator, callback) {
- if (arguments.length === 3) {
- callback = iterator;
- iterator = memo;
- memo = _isArray(arr) ? [] : {};
- }
-
- async.eachOf(arr, function(v, k, cb) {
- iterator(memo, v, k, cb);
- }, function(err) {
- callback(err, memo);
- });
- };
-
- function _filter(eachfn, arr, iterator, callback) {
- var results = [];
- eachfn(arr, function (x, index, callback) {
- iterator(x, function (v) {
- if (v) {
- results.push({index: index, value: x});
- }
- callback();
- });
- }, function () {
- callback(_map(results.sort(function (a, b) {
- return a.index - b.index;
- }), function (x) {
- return x.value;
- }));
- });
- }
-
- async.select =
- async.filter = doParallel(_filter);
-
- async.selectLimit =
- async.filterLimit = doParallelLimit(_filter);
-
- async.selectSeries =
- async.filterSeries = doSeries(_filter);
-
- function _reject(eachfn, arr, iterator, callback) {
- _filter(eachfn, arr, function(value, cb) {
- iterator(value, function(v) {
- cb(!v);
- });
- }, callback);
- }
- async.reject = doParallel(_reject);
- async.rejectLimit = doParallelLimit(_reject);
- async.rejectSeries = doSeries(_reject);
-
- 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);
- }
- };
- }
-
- async.any =
- async.some = _createTester(async.eachOf, toBool, identity);
-
- async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
-
- async.all =
- async.every = _createTester(async.eachOf, notId, notId);
-
- async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
-
- function _findGetResult(v, x) {
- return x;
- }
- async.detect = _createTester(async.eachOf, identity, _findGetResult);
- async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
- async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
-
- async.sortBy = function (arr, iterator, callback) {
- async.map(arr, function (x, callback) {
- iterator(x, function (err, criteria) {
- if (err) {
- callback(err);
- }
- else {
- callback(null, {value: x, criteria: criteria});
- }
- });
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
- else {
- callback(null, _map(results.sort(comparator), function (x) {
- return x.value;
- }));
- }
-
- });
-
- function comparator(left, right) {
- var a = left.criteria, b = right.criteria;
- return a < b ? -1 : a > b ? 1 : 0;
- }
- };
-
- async.auto = 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 = _keys(tasks);
- var remainingTasks = keys.length;
- if (!remainingTasks) {
- return callback(null);
- }
- if (!concurrency) {
- concurrency = remainingTasks;
- }
-
- var results = {};
- var runningTasks = 0;
-
- var hasError = false;
-
- 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(0), function (fn) {
- fn();
- });
- }
-
- addListener(function () {
- if (!remainingTasks) {
- callback(null, results);
- }
- });
-
- _arrayEach(keys, function (k) {
- if (hasError) return;
- var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
- var taskCallback = _restParam(function(err, args) {
- runningTasks--;
- if (args.length <= 1) {
- args = args[0];
- }
- if (err) {
- var safeResults = {};
- _forEachOf(results, function(val, rkey) {
- safeResults[rkey] = val;
- });
- safeResults[k] = args;
- hasError = true;
-
- callback(err, safeResults);
- }
- else {
- results[k] = args;
- async.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 && _reduce(requires, function (a, x) {
- return (a && results.hasOwnProperty(x));
- }, true) && !results.hasOwnProperty(k);
- }
- 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);
- }
- }
- });
- };
-
-
-
- async.retry = function(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));
- }
- }
-
- async.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;
- };
-
- async.waterfall = function (tasks, callback) {
- callback = _once(callback || noop);
- if (!_isArray(tasks)) {
- var err = new Error('First argument to waterfall must be an array of functions');
- return callback(err);
- }
- if (!tasks.length) {
- return callback();
- }
- function wrapIterator(iterator) {
- return _restParam(function (err, args) {
- if (err) {
- callback.apply(null, [err].concat(args));
- }
- else {
- var next = iterator.next();
- if (next) {
- args.push(wrapIterator(next));
- }
- else {
- args.push(callback);
- }
- ensureAsync(iterator).apply(null, args);
- }
- });
- }
- wrapIterator(async.iterator(tasks))();
- };
-
- function _parallel(eachfn, tasks, callback) {
- callback = callback || noop;
- var results = _isArrayLike(tasks) ? [] : {};
-
- eachfn(tasks, function (task, key, callback) {
- task(_restParam(function (err, args) {
- if (args.length <= 1) {
- args = args[0];
- }
- results[key] = args;
- callback(err);
- }));
- }, function (err) {
- callback(err, results);
- });
+ if (isSymbol(value)) {
+ return Symbol ? symbolToString.call(value) : '';
}
-
- async.parallel = function (tasks, callback) {
- _parallel(async.eachOf, tasks, callback);
- };
-
- async.parallelLimit = function(tasks, limit, callback) {
- _parallel(_eachOfLimit(limit), tasks, callback);
- };
-
- async.series = function(tasks, callback) {
- _parallel(async.eachOfSeries, tasks, callback);
- };
-
- async.iterator = 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);
- };
-
- async.apply = _restParam(function (fn, args) {
- return _restParam(function (callArgs) {
- return fn.apply(
- null, args.concat(callArgs)
- );
- });
+ var result = (value + '');
+ return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
+ }
+
+ /** Used to match property names within property paths. */
+ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;
+
+ /** Used to match backslashes in property paths. */
+ var reEscapeChar = /\\(\\)?/g;
+
+ /**
+ * Converts `string` to a property path array.
+ *
+ * @private
+ * @param {string} string The string to convert.
+ * @returns {Array} Returns the property path array.
+ */
+ function stringToPath(string) {
+ var result = [];
+ toString(string).replace(rePropName, function(match, number, quote, string) {
+ result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
-
- 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);
- });
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.toPath` which only converts `value` to a
+ * path if it's not one.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {Array} Returns the property path array.
+ */
+ function baseToPath(value) {
+ return isArray(value) ? value : stringToPath(value);
+ }
+
+ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
+ var reIsPlainProp = /^\w*$/;
+ /**
+ * Checks if `value` is a property name and not a property path.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {Object} [object] The object to query keys on.
+ * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
+ */
+ function isKey(value, object) {
+ if (typeof value == 'number') {
+ return true;
}
- async.concat = doParallel(_concat);
- async.concatSeries = doSeries(_concat);
-
- async.whilst = function (test, iterator, callback) {
- callback = callback || noop;
- if (test()) {
- var next = _restParam(function(err, args) {
- if (err) {
- callback(err);
- } else if (test.apply(this, args)) {
- iterator(next);
- } else {
- callback.apply(null, [null].concat(args));
- }
- });
- iterator(next);
- } else {
- callback(null);
- }
- };
-
- async.doWhilst = function (iterator, test, callback) {
- var calls = 0;
- return async.whilst(function() {
- return ++calls <= 1 || test.apply(this, arguments);
- }, iterator, callback);
- };
-
- async.until = function (test, iterator, callback) {
- return async.whilst(function() {
- return !test.apply(this, arguments);
- }, iterator, callback);
- };
-
- async.doUntil = function (iterator, test, callback) {
- return async.doWhilst(iterator, function() {
- return !test.apply(this, arguments);
- }, callback);
- };
-
- async.during = function (test, iterator, callback) {
- callback = callback || noop;
-
- var next = _restParam(function(err, args) {
- if (err) {
- callback(err);
- } else {
- args.push(check);
- test.apply(this, args);
- }
- });
-
- var check = function(err, truth) {
- if (err) {
- callback(err);
- } else if (truth) {
- iterator(next);
- } else {
- callback(null);
- }
- };
-
- test(check);
- };
-
- async.doDuring = function (iterator, test, callback) {
- var calls = 0;
- async.during(function(next) {
- if (calls++ < 1) {
- next(null, true);
- } else {
- test.apply(this, arguments);
- }
- }, iterator, callback);
- };
-
- 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 async.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();
- }
- });
- async.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 = _map(tasks, function (task) {
- return task.data;
- });
-
- if (q.tasks.length === 0) {
- q.empty();
- }
- workers += 1;
- workersList.push(tasks[0]);
- var cb = only_once(_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++) {
- async.setImmediate(q.process);
- }
- }
- };
- return q;
+ return !isArray(value) &&
+ (reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
+ (object != null && value in Object(object)));
+ }
+
+ /**
+ * Gets the last element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {*} Returns the last element of `array`.
+ * @example
+ *
+ * _.last([1, 2, 3]);
+ * // => 3
+ */
+ function last(array) {
+ var length = array ? array.length : 0;
+ return length ? array[length - 1] : undefined;
+ }
+
+ /**
+ * The base implementation of `_.slice` without an iteratee call guard.
+ *
+ * @private
+ * @param {Array} array The array to slice.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns the slice of `array`.
+ */
+ function baseSlice(array, start, end) {
+ var index = -1,
+ length = array.length;
+
+ if (start < 0) {
+ start = -start > length ? 0 : (length + start);
}
-
- async.queue = function (worker, concurrency) {
- var q = _queue(function (items, cb) {
- worker(items[0], cb);
- }, concurrency, 1);
-
- return q;
- };
-
- async.priorityQueue = 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 async.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();
- }
- async.setImmediate(q.process);
- });
- }
-
- // Start with a normal queue
- var q = async.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;
- };
-
- async.cargo = function (worker, payload) {
- return _queue(worker, 1, payload);
- };
-
- function _console_fn(name) {
- return _restParam(function (fn, args) {
- fn.apply(null, args.concat([_restParam(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);
- });
- }
- }
- })]));
- });
+ end = end > length ? length : end;
+ if (end < 0) {
+ end += length;
}
- async.log = _console_fn('log');
- async.dir = _console_fn('dir');
- /*async.info = _console_fn('info');
- async.warn = _console_fn('warn');
- async.error = _console_fn('error');*/
-
- async.memoize = function (fn, hasher) {
- var memo = {};
- var queues = {};
- hasher = hasher || identity;
- var memoized = _restParam(function memoized(args) {
- var callback = args.pop();
- var key = hasher.apply(null, args);
- if (key in memo) {
- async.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([_restParam(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;
- };
+ length = start > end ? 0 : ((end - start) >>> 0);
+ start >>>= 0;
- async.unmemoize = function (fn) {
- return function () {
- return (fn.unmemoized || fn).apply(null, arguments);
- };
- };
-
- function _times(mapper) {
- return function (count, iterator, callback) {
- mapper(_range(count), iterator, callback);
- };
+ var result = Array(length);
+ while (++index < length) {
+ result[index] = array[index + start];
}
-
- async.times = _times(async.map);
- async.timesSeries = _times(async.mapSeries);
- async.timesLimit = function (count, limit, iterator, callback) {
- return async.mapLimit(_range(count), limit, iterator, callback);
- };
-
- async.seq = function (/* functions... */) {
- var fns = arguments;
- return _restParam(function (args) {
- var that = this;
-
- var callback = args[args.length - 1];
- if (typeof callback == 'function') {
- args.pop();
- } else {
- callback = noop;
- }
-
- async.reduce(fns, args, function (newargs, fn, cb) {
- fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
- cb(err, nextargs);
- })]));
- },
- function (err, results) {
- callback.apply(that, [err].concat(results));
- });
- });
- };
-
- async.compose = function (/* functions... */) {
- return async.seq.apply(null, Array.prototype.reverse.call(arguments));
- };
-
-
- function _applyEach(eachfn) {
- return _restParam(function(fns, args) {
- var go = _restParam(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;
- }
- });
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.get` without support for default values.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to get.
+ * @returns {*} Returns the resolved value.
+ */
+ function baseGet(object, path) {
+ path = isKey(path, object) ? [path + ''] : baseToPath(path);
+
+ var index = 0,
+ length = path.length;
+
+ while (object != null && index < length) {
+ object = object[path[index++]];
}
-
- async.applyEach = _applyEach(async.eachOf);
- async.applyEachSeries = _applyEach(async.eachOfSeries);
-
-
- async.forever = function (fn, callback) {
- var done = only_once(callback || noop);
- var task = ensureAsync(fn);
- function next(err) {
- if (err) {
- return done(err);
- }
- task(next);
- }
- next();
- };
-
- function ensureAsync(fn) {
- return _restParam(function (args) {
- var callback = args.pop();
- args.push(function () {
- var innerArgs = arguments;
- if (sync) {
- async.setImmediate(function () {
- callback.apply(null, innerArgs);
- });
- } else {
- callback.apply(null, innerArgs);
- }
- });
- var sync = true;
- fn.apply(this, args);
- sync = false;
- });
+ return (index && index == length) ? object : undefined;
+ }
+
+ /**
+ * Gets the value at `path` of `object`. If the resolved value is
+ * `undefined` the `defaultValue` is used in its place.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to get.
+ * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
+ * @returns {*} Returns the resolved value.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': 3 } }] };
+ *
+ * _.get(object, 'a[0].b.c');
+ * // => 3
+ *
+ * _.get(object, ['a', '0', 'b', 'c']);
+ * // => 3
+ *
+ * _.get(object, 'a.b.c', 'default');
+ * // => 'default'
+ */
+ function get(object, path, defaultValue) {
+ var result = object == null ? undefined : baseGet(object, path);
+ return result === undefined ? defaultValue : result;
+ }
+
+ /**
+ * Gets the parent value at `path` of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} path The path to get the parent value of.
+ * @returns {*} Returns the parent value.
+ */
+ function parent(object, path) {
+ return path.length == 1 ? object : get(object, baseSlice(path, 0, -1));
+ }
+
+ /**
+ * Checks if `path` exists on `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @param {Function} hasFunc The function to check properties.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
+ */
+ function hasPath(object, path, hasFunc) {
+ if (object == null) {
+ return false;
}
-
- async.ensureAsync = ensureAsync;
-
- async.constant = _restParam(function(values) {
- var args = [null].concat(values);
- return function (callback) {
- return callback.apply(this, args);
- };
- });
-
- async.wrapSync =
- async.asyncify = function asyncify(func) {
- return _restParam(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);
- }
- });
- };
-
- // Node.js
- if (typeof module === 'object' && module.exports) {
- module.exports = async;
+ var result = hasFunc(object, path);
+ if (!result && !isKey(path)) {
+ path = baseToPath(path);
+ object = parent(object, path);
+ if (object != null) {
+ path = last(path);
+ result = hasFunc(object, path);
+ }
}
- // AMD / RequireJS
- else if (typeof define === 'function' && define.amd) {
- define([], function () {
- return async;
- });
+ var length = object ? object.length : undefined;
+ return result || (
+ !!length && isLength(length) && isIndex(path, length) &&
+ (isArray(object) || isString(object) || isArguments(object))
+ );
+ }
+
+ /**
+ * Checks if `path` is a direct property of `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
+ * @example
+ *
+ * var object = { 'a': { 'b': { 'c': 3 } } };
+ * var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });
+ *
+ * _.has(object, 'a');
+ * // => true
+ *
+ * _.has(object, 'a.b.c');
+ * // => true
+ *
+ * _.has(object, ['a', 'b', 'c']);
+ * // => true
+ *
+ * _.has(other, 'a');
+ * // => false
+ */
+ function has(object, path) {
+ return hasPath(object, path, baseHas);
+ }
+
+ function memoize(fn, hasher) {
+ var memo = Object.create(null);
+ var queues = Object.create(null);
+ hasher = hasher || identity;
+ var memoized = rest(function memoized(args) {
+ var callback = args.pop();
+ var key = hasher.apply(null, args);
+ if (has(memo, key)) {
+ setImmediate$1(function () {
+ callback.apply(null, memo[key]);
+ });
+ } else if (has(queues, key)) {
+ 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;
+ }
+
+ var nexTick = typeof process === 'object' && typeof process.nextTick === 'function' ? process.nextTick : setImmediate$1;
+
+ 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);
+ });
+ }
+
+ function parallel(tasks, cb) {
+ return _parallel(eachOf, tasks, cb);
+ }
+
+ function parallelLimit(tasks, limit, cb) {
+ return _parallel(_eachOfLimit(limit), tasks, cb);
+ }
+
+ function queue (worker, concurrency) {
+ return queue$1(function (items, cb) {
+ worker(items[0], cb);
+ }, concurrency, 1);
+ }
+
+ function priorityQueue (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$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);
+ });
+ }
+
+ // 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;
+ }
+
+ var slice = Array.prototype.slice;
+
+ function reduceRight(arr, memo, iterator, cb) {
+ var reversed = slice.call(arr).reverse();
+ reduce(reversed, memo, iterator, cb);
+ }
+
+ function reject$1(eachfn, arr, iterator, callback) {
+ _filter(eachfn, arr, function (value, cb) {
+ iterator(value, function (err, v) {
+ if (err) {
+ cb(err);
+ } else {
+ cb(null, !v);
+ }
+ });
+ }, callback);
+ }
+
+ var reject = doParallel(reject$1);
+
+ 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);
+ }
+ }
+
+ 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;
+ }
+
+ var some = _createTester(eachOf, Boolean, identity);
+
+ 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 });
+ });
+ }, 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;
+ }
+ }
+
+ /* 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);
+
+ while (length--) {
+ result[fromRight ? length : ++index] = start;
+ start += step;
}
- // included directly via <script> tag
- else {
- root.async = async;
- }
-
-}());
+ 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,
+ 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: nexTick,
+ 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$1,
+ some: some,
+ someLimit: someLimit,
+ sortBy: sortBy,
+ times: times,
+ timesLimit: timeLimit,
+ 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
+ };
+
+ exports['default'] = index;
+ exports.applyEach = applyEach;
+ exports.applyEachSeries = applyEachSeries;
+ exports.apply = apply;
+ exports.asyncify = asyncify;
+ exports.auto = auto;
+ exports.cargo = cargo;
+ exports.compose = compose;
+ exports.concat = concat;
+ exports.concatSeries = concatSeries;
+ exports.constant = constant;
+ exports.detect = detect;
+ exports.detectLimit = detectLimit;
+ exports.detectSeries = detectSeries;
+ exports.dir = dir;
+ exports.doDuring = doDuring;
+ exports.doUntil = doUntil;
+ exports.doWhilst = doWhilst;
+ exports.during = during;
+ exports.each = each;
+ exports.eachLimit = eachLimit;
+ exports.eachOf = eachOf;
+ exports.eachOfLimit = eachOfLimit;
+ exports.eachOfSeries = eachOfSeries;
+ exports.eachSeries = eachSeries;
+ exports.ensureAsync = ensureAsync;
+ exports.every = every;
+ exports.everyLimit = everyLimit;
+ exports.filter = filter;
+ exports.filterLimit = filterLimit;
+ exports.filterSeries = filterSeries;
+ exports.forever = forever;
+ exports.iterator = iterator;
+ exports.log = log;
+ exports.map = map;
+ exports.mapLimit = mapLimit;
+ exports.mapSeries = mapSeries;
+ exports.memoize = memoize;
+ exports.nextTick = nexTick;
+ exports.parallel = parallel;
+ exports.parallelLimit = parallelLimit;
+ exports.priorityQueue = priorityQueue;
+ exports.queue = queue;
+ exports.reduce = reduce;
+ exports.reduceRight = reduceRight;
+ exports.reject = reject;
+ exports.rejectLimit = rejectLimit;
+ exports.rejectSeries = rejectSeries;
+ exports.retry = retry;
+ exports.seq = seq;
+ exports.series = series;
+ exports.setImmediate = setImmediate$1;
+ exports.some = some;
+ exports.someLimit = someLimit;
+ exports.sortBy = sortBy;
+ exports.times = times;
+ exports.timesLimit = timeLimit;
+ exports.timesSeries = timesSeries;
+ exports.transform = transform;
+ exports.unmemoize = unmemoize;
+ exports.until = until;
+ exports.waterfall = waterfall;
+ exports.whilst = whilst;
+ exports.all = every;
+ exports.any = some;
+ exports.forEach = each;
+ exports.forEachSeries = eachSeries;
+ exports.forEachLimit = eachLimit;
+ exports.forEachOf = eachOf;
+ exports.forEachOfSeries = eachOfSeries;
+ exports.forEachOfLimit = eachOfLimit;
+ exports.inject = reduce;
+ exports.foldl = reduce;
+ exports.foldr = reduceRight;
+ exports.select = filter;
+ exports.selectLimit = filterLimit;
+ exports.selectSeries = filterSeries;
+ exports.wrapSync = asyncify;
+
+})); \ No newline at end of file
diff --git a/dist/async.min.js b/dist/async.min.js
index 9b0028d..2915a67 100644
--- a/dist/async.min.js
+++ b/dist/async.min.js
@@ -1,2 +1,2 @@
-!function(){function n(){}function t(n){return n}function e(n){return!!n}function r(n){return!n}function u(n){return function(){if(null===n)throw new Error("Callback was already called.");n.apply(this,arguments),n=null}}function i(n){return function(){null!==n&&(n.apply(this,arguments),n=null)}}function o(n){return M(n)||"number"==typeof n.length&&n.length>=0&&n.length%1===0}function c(n,t){for(var e=-1,r=n.length;++e<r;)t(n[e],e,n)}function a(n,t){for(var e=-1,r=n.length,u=Array(r);++e<r;)u[e]=t(n[e],e,n);return u}function f(n){return a(Array(n),function(n,t){return t})}function l(n,t,e){return c(n,function(n,r,u){e=t(e,n,r,u)}),e}function s(n,t){c(W(n),function(e){t(n[e],e)})}function p(n,t){for(var e=0;e<n.length;e++)if(n[e]===t)return e;return-1}function h(n){var t,e,r=-1;return o(n)?(t=n.length,function(){return r++,t>r?r:null}):(e=W(n),t=e.length,function(){return r++,t>r?e[r]:null})}function m(n,t){return t=null==t?n.length-1:+t,function(){for(var e=Math.max(arguments.length-t,0),r=Array(e),u=0;e>u;u++)r[u]=arguments[u+t];switch(t){case 0:return n.call(this,r);case 1:return n.call(this,arguments[0],r)}}}function y(n){return function(t,e,r){return n(t,r)}}function v(t){return function(e,r,o){o=i(o||n),e=e||[];var c=h(e);if(0>=t)return o(null);var a=!1,f=0,l=!1;!function s(){if(a&&0>=f)return o(null);for(;t>f&&!l;){var n=c();if(null===n)return a=!0,void(0>=f&&o(null));f+=1,r(e[n],n,u(function(n){f-=1,n?(o(n),l=!0):s()}))}}()}}function d(n){return function(t,e,r){return n(C.eachOf,t,e,r)}}function g(n){return function(t,e,r,u){return n(v(e),t,r,u)}}function k(n){return function(t,e,r){return n(C.eachOfSeries,t,e,r)}}function b(t,e,r,u){u=i(u||n),e=e||[];var c=o(e)?[]:{};t(e,function(n,t,e){r(n,function(n,r){c[t]=r,e(n)})},function(n){u(n,c)})}function w(n,t,e,r){var u=[];n(t,function(n,t,r){e(n,function(e){e&&u.push({index:t,value:n}),r()})},function(){r(a(u.sort(function(n,t){return n.index-t.index}),function(n){return n.value}))})}function O(n,t,e,r){w(n,t,function(n,t){e(n,function(n){t(!n)})},r)}function S(n,t,e){return function(r,u,i,o){function c(){o&&o(e(!1,void 0))}function a(n,r,u){return o?void i(n,function(r){o&&t(r)&&(o(e(!0,n)),o=i=!1),u()}):u()}arguments.length>3?n(r,u,a,c):(o=i,i=u,n(r,a,c))}}function E(n,t){return t}function L(t,e,r){r=r||n;var u=o(e)?[]:{};t(e,function(n,t,e){n(m(function(n,r){r.length<=1&&(r=r[0]),u[t]=r,e(n)}))},function(n){r(n,u)})}function I(n,t,e,r){var u=[];n(t,function(n,t,r){e(n,function(n,t){u=u.concat(t||[]),r(n)})},function(n){r(n,u)})}function x(t,e,r){function i(t,e,r,u){if(null!=u&&"function"!=typeof u)throw new Error("task callback must be a function");return t.started=!0,M(e)||(e=[e]),0===e.length&&t.idle()?C.setImmediate(function(){t.drain()}):(c(e,function(e){var i={data:e,callback:u||n};r?t.tasks.unshift(i):t.tasks.push(i),t.tasks.length===t.concurrency&&t.saturated()}),void C.setImmediate(t.process))}function o(n,t){return function(){f-=1;var e=!1,r=arguments;c(t,function(n){c(l,function(t,r){t!==n||e||(l.splice(r,1),e=!0)}),n.callback.apply(n,r)}),n.tasks.length+f===0&&n.drain(),n.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var f=0,l=[],s={tasks:[],concurrency:e,payload:r,saturated:n,empty:n,drain:n,started:!1,paused:!1,push:function(n,t){i(s,n,!1,t)},kill:function(){s.drain=n,s.tasks=[]},unshift:function(n,t){i(s,n,!0,t)},process:function(){for(;!s.paused&&f<s.concurrency&&s.tasks.length;){var n=s.payload?s.tasks.splice(0,s.payload):s.tasks.splice(0,s.tasks.length),e=a(n,function(n){return n.data});0===s.tasks.length&&s.empty(),f+=1,l.push(n[0]);var r=u(o(s,n));t(e,r)}},length:function(){return s.tasks.length},running:function(){return f},workersList:function(){return l},idle:function(){return s.tasks.length+f===0},pause:function(){s.paused=!0},resume:function(){if(s.paused!==!1){s.paused=!1;for(var n=Math.min(s.concurrency,s.tasks.length),t=1;n>=t;t++)C.setImmediate(s.process)}}};return s}function j(n){return m(function(t,e){t.apply(null,e.concat([m(function(t,e){"object"==typeof console&&(t?console.error&&console.error(t):console[n]&&c(e,function(t){console[n](t)}))})]))})}function A(n){return function(t,e,r){n(f(t),e,r)}}function T(n){return m(function(t,e){var r=m(function(e){var r=this,u=e.pop();return n(t,function(n,t,u){n.apply(r,e.concat([u]))},u)});return e.length?r.apply(this,e):r})}function z(n){return m(function(t){var e=t.pop();t.push(function(){var n=arguments;r?C.setImmediate(function(){e.apply(null,n)}):e.apply(null,n)});var r=!0;n.apply(this,t),r=!1})}var q,C={},P="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||this;null!=P&&(q=P.async),C.noConflict=function(){return P.async=q,C};var H=Object.prototype.toString,M=Array.isArray||function(n){return"[object Array]"===H.call(n)},U=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},W=Object.keys||function(n){var t=[];for(var e in n)n.hasOwnProperty(e)&&t.push(e);return t},B="function"==typeof setImmediate&&setImmediate,D=B?function(n){B(n)}:function(n){setTimeout(n,0)};"object"==typeof process&&"function"==typeof process.nextTick?C.nextTick=process.nextTick:C.nextTick=D,C.setImmediate=B?D:C.nextTick,C.forEach=C.each=function(n,t,e){return C.eachOf(n,y(t),e)},C.forEachSeries=C.eachSeries=function(n,t,e){return C.eachOfSeries(n,y(t),e)},C.forEachLimit=C.eachLimit=function(n,t,e,r){return v(t)(n,y(e),r)},C.forEachOf=C.eachOf=function(t,e,r){function o(n){f--,n?r(n):null===c&&0>=f&&r(null)}r=i(r||n),t=t||[];for(var c,a=h(t),f=0;null!=(c=a());)f+=1,e(t[c],c,u(o));0===f&&r(null)},C.forEachOfSeries=C.eachOfSeries=function(t,e,r){function o(){var n=!0;return null===a?r(null):(e(t[a],a,u(function(t){if(t)r(t);else{if(a=c(),null===a)return r(null);n?C.setImmediate(o):o()}})),void(n=!1))}r=i(r||n),t=t||[];var c=h(t),a=c();o()},C.forEachOfLimit=C.eachOfLimit=function(n,t,e,r){v(t)(n,e,r)},C.map=d(b),C.mapSeries=k(b),C.mapLimit=g(b),C.inject=C.foldl=C.reduce=function(n,t,e,r){C.eachOfSeries(n,function(n,r,u){e(t,n,function(n,e){t=e,u(n)})},function(n){r(n,t)})},C.foldr=C.reduceRight=function(n,e,r,u){var i=a(n,t).reverse();C.reduce(i,e,r,u)},C.transform=function(n,t,e,r){3===arguments.length&&(r=e,e=t,t=M(n)?[]:{}),C.eachOf(n,function(n,r,u){e(t,n,r,u)},function(n){r(n,t)})},C.select=C.filter=d(w),C.selectLimit=C.filterLimit=g(w),C.selectSeries=C.filterSeries=k(w),C.reject=d(O),C.rejectLimit=g(O),C.rejectSeries=k(O),C.any=C.some=S(C.eachOf,e,t),C.someLimit=S(C.eachOfLimit,e,t),C.all=C.every=S(C.eachOf,r,r),C.everyLimit=S(C.eachOfLimit,r,r),C.detect=S(C.eachOf,t,E),C.detectSeries=S(C.eachOfSeries,t,E),C.detectLimit=S(C.eachOfLimit,t,E),C.sortBy=function(n,t,e){function r(n,t){var e=n.criteria,r=t.criteria;return r>e?-1:e>r?1:0}C.map(n,function(n,e){t(n,function(t,r){t?e(t):e(null,{value:n,criteria:r})})},function(n,t){return n?e(n):void e(null,a(t.sort(r),function(n){return n.value}))})},C.auto=function(t,e,r){function u(n){g.unshift(n)}function o(n){var t=p(g,n);t>=0&&g.splice(t,1)}function a(){h--,c(g.slice(0),function(n){n()})}"function"==typeof arguments[1]&&(r=e,e=null),r=i(r||n);var f=W(t),h=f.length;if(!h)return r(null);e||(e=h);var y={},v=0,d=!1,g=[];u(function(){h||r(null,y)}),c(f,function(n){function i(){return e>v&&l(k,function(n,t){return n&&y.hasOwnProperty(t)},!0)&&!y.hasOwnProperty(n)}function c(){i()&&(v++,o(c),h[h.length-1](g,y))}if(!d){for(var f,h=M(t[n])?t[n]:[t[n]],g=m(function(t,e){if(v--,e.length<=1&&(e=e[0]),t){var u={};s(y,function(n,t){u[t]=n}),u[n]=e,d=!0,r(t,u)}else y[n]=e,C.setImmediate(a)}),k=h.slice(0,h.length-1),b=k.length;b--;){if(!(f=t[k[b]]))throw new Error("Has inexistant dependency");if(M(f)&&p(f,n)>=0)throw new Error("Has cyclic dependencies")}i()?(v++,h[h.length-1](g,y)):u(c)}})},C.retry=function(n,t,e){function r(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 e(n,e){return function(r){n(function(n,t){r(!n||e,{err:n,result:t})},t)}}function r(n){return function(t){setTimeout(function(){t(null)},n)}}for(;a.times;){var u=!(a.times-=1);c.push(e(a.task,u)),!u&&a.interval>0&&c.push(r(a.interval))}C.series(c,function(t,e){e=e[e.length-1],(n||a.callback)(e.err,e.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&&(e=t,t=n),"function"!=typeof n&&r(a,n),a.callback=e,a.task=t,a.callback?u():u},C.waterfall=function(t,e){function r(n){return m(function(t,u){if(t)e.apply(null,[t].concat(u));else{var i=n.next();i?u.push(r(i)):u.push(e),z(n).apply(null,u)}})}if(e=i(e||n),!M(t)){var u=new Error("First argument to waterfall must be an array of functions");return e(u)}return t.length?void r(C.iterator(t))():e()},C.parallel=function(n,t){L(C.eachOf,n,t)},C.parallelLimit=function(n,t,e){L(v(t),n,e)},C.series=function(n,t){L(C.eachOfSeries,n,t)},C.iterator=function(n){function t(e){function r(){return n.length&&n[e].apply(null,arguments),r.next()}return r.next=function(){return e<n.length-1?t(e+1):null},r}return t(0)},C.apply=m(function(n,t){return m(function(e){return n.apply(null,t.concat(e))})}),C.concat=d(I),C.concatSeries=k(I),C.whilst=function(t,e,r){if(r=r||n,t()){var u=m(function(n,i){n?r(n):t.apply(this,i)?e(u):r.apply(null,[null].concat(i))});e(u)}else r(null)},C.doWhilst=function(n,t,e){var r=0;return C.whilst(function(){return++r<=1||t.apply(this,arguments)},n,e)},C.until=function(n,t,e){return C.whilst(function(){return!n.apply(this,arguments)},t,e)},C.doUntil=function(n,t,e){return C.doWhilst(n,function(){return!t.apply(this,arguments)},e)},C.during=function(t,e,r){r=r||n;var u=m(function(n,e){n?r(n):(e.push(i),t.apply(this,e))}),i=function(n,t){n?r(n):t?e(u):r(null)};t(i)},C.doDuring=function(n,t,e){var r=0;C.during(function(n){r++<1?n(null,!0):t.apply(this,arguments)},n,e)},C.queue=function(n,t){var e=x(function(t,e){n(t[0],e)},t,1);return e},C.priorityQueue=function(t,e){function r(n,t){return n.priority-t.priority}function u(n,t,e){for(var r=-1,u=n.length-1;u>r;){var i=r+(u-r+1>>>1);e(t,n[i])>=0?r=i:u=i-1}return r}function i(t,e,i,o){if(null!=o&&"function"!=typeof o)throw new Error("task callback must be a function");return t.started=!0,M(e)||(e=[e]),0===e.length?C.setImmediate(function(){t.drain()}):void c(e,function(e){var c={data:e,priority:i,callback:"function"==typeof o?o:n};t.tasks.splice(u(t.tasks,c,r)+1,0,c),t.tasks.length===t.concurrency&&t.saturated(),C.setImmediate(t.process)})}var o=C.queue(t,e);return o.push=function(n,t,e){i(o,n,t,e)},delete o.unshift,o},C.cargo=function(n,t){return x(n,1,t)},C.log=j("log"),C.dir=j("dir"),C.memoize=function(n,e){var r={},u={};e=e||t;var i=m(function(t){var i=t.pop(),o=e.apply(null,t);o in r?C.setImmediate(function(){i.apply(null,r[o])}):o in u?u[o].push(i):(u[o]=[i],n.apply(null,t.concat([m(function(n){r[o]=n;var t=u[o];delete u[o];for(var e=0,i=t.length;i>e;e++)t[e].apply(null,n)})])))});return i.memo=r,i.unmemoized=n,i},C.unmemoize=function(n){return function(){return(n.unmemoized||n).apply(null,arguments)}},C.times=A(C.map),C.timesSeries=A(C.mapSeries),C.timesLimit=function(n,t,e,r){return C.mapLimit(f(n),t,e,r)},C.seq=function(){var t=arguments;return m(function(e){var r=this,u=e[e.length-1];"function"==typeof u?e.pop():u=n,C.reduce(t,e,function(n,t,e){t.apply(r,n.concat([m(function(n,t){e(n,t)})]))},function(n,t){u.apply(r,[n].concat(t))})})},C.compose=function(){return C.seq.apply(null,Array.prototype.reverse.call(arguments))},C.applyEach=T(C.eachOf),C.applyEachSeries=T(C.eachOfSeries),C.forever=function(t,e){function r(n){return n?i(n):void o(r)}var i=u(e||n),o=z(t);r()},C.ensureAsync=z,C.constant=m(function(n){var t=[null].concat(n);return function(n){return n.apply(this,t)}}),C.wrapSync=C.asyncify=function(n){return m(function(t){var e,r=t.pop();try{e=n.apply(this,t)}catch(u){return r(u)}U(e)&&"function"==typeof e.then?e.then(function(n){r(null,n)})["catch"](function(n){r(n.message?n:new Error(n))}):r(null,e)})},"object"==typeof module&&module.exports?module.exports=C:"function"==typeof define&&define.amd?define([],function(){return C}):P.async=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.length;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)?nt.call(n):"";return t==Yn||t==Zn}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(rt,"");var u=ut.test(n);return u||it.test(n)?ot(n.slice(2),u?2:8):et.test(n)?tt:+n}function i(n){if(!n)return 0===n?n:0;if(n=u(n),n===ct||n===-ct){var t=0>n?-1:1;return t*ft}var r=n%1;return n===n?r?n-r:n:0}function o(n,r){if("function"!=typeof n)throw new TypeError(at);return r=lt(void 0===r?n.length-1:i(r),0),function(){for(var e=arguments,u=-1,i=lt(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 f(n,t){var r;if("function"!=typeof t)throw new TypeError(st);return n=i(n),function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=void 0),r}}function a(n){return f(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&&yt>=n}function y(n){return null!=n&&!("function"==typeof n&&e(n))&&p(pt(n))}function h(n,t){return vt.call(n,t)||"object"==typeof n&&t in n&&null===mt(n)}function v(n){return dt(Object(n))}function m(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)&&y(n)}function b(n){return g(n)&&kt.call(n,"callee")&&(!jt.call(n,"callee")||wt.call(n)==gt)}function k(n){return"string"==typeof n||!St(n)&&d(n)&&Lt.call(n)==Ot}function w(n){var t=n?n.length:void 0;return p(t)&&(St(n)||k(n)||b(n))?m(t,String):null}function j(n,t){return n="number"==typeof n||At.test(n)?+n:-1,t=null==t?xt:t,n>-1&&n%1==0&&t>n}function S(n){var t=n&&n.constructor,r="function"==typeof t&&t.prototype||Tt;return n===r}function O(n){var t=S(n);if(!t&&!y(n))return v(n);var r=w(n),e=!!r,u=r||[],i=u.length;for(var o in n)!h(n,o)||e&&("length"==o||j(o,i))||t&&"constructor"==o||u.push(o);return u}function E(n){var t,r=-1;if(y(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 L(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=a(r||l),n=n||[];for(var u,i=E(n),o=0;null!=(u=i());)o+=1,t(n[u],u,L(e));0===o&&r(null)}function A(n,t,r){function e(){var o=!0;return null===i?r(null):(t(n[i],i,L(function(n){if(n)r(n);else{if(i=u(),null===i)return r(null);o?$t(e):e()}})),void(o=!1))}r=a(r||l),n=n||[];var u=E(n),i=u();e()}function T(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 I(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 $(n){return function(t,r,e){for(var u=-1,i=Object(t),o=e(t),c=o.length;c--;){var f=o[n?c:++u];if(r(i[f],f,i)===!1)break}return t}}function M(n,t){return n&&Bt(n,t,O)}function q(n){return n}function B(n){return"function"==typeof n?n:q}function F(n,t){return n&&M(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=Ft(e+r,0)),U(n,t,r)):-1}function D(n,t,r){function e(n){v.unshift(n)}function u(n){var t=C(v,n);t>=0&&v.splice(t,1)}function i(){f--,I(v.slice(),function(n){n()})}"function"==typeof arguments[1]&&(r=t,t=null),r=a(r||l);var c=O(n),f=c.length;if(!f)return r(null);t||(t=f);var s={},p=0,y=!1,v=[];e(function(){f||r(null,s)}),I(c,function(c){function f(){return t>p&&!h(s,c)&&z(d,function(n){return h(s,n)})}function a(){f()&&(p++,u(a),v[v.length-1](m,s))}if(!y){for(var l,v=St(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,y=!0,r(n,e)}else s[c]=t,$t(i)}),d=v.slice(0,v.length-1),g=d.length;g--;){if(!(l=n[d[g]]))throw new Error("Has non-existent dependency in "+d.join(", "));if(St(l)&&C(l,c)>=0)throw new Error("Has cyclic dependencies")}f()?(p++,v[v.length-1](m,s)):e(a)}})}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,St(t)||(t=[t]),0===t.length&&n.idle()?$t(function(){n.drain()}):(I(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 $t(n.process))}function u(n,t){return function(){i-=1;var r=!1,e=arguments;I(t,function(n){I(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=L(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++)$t(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,Pt.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(n){o&&(n?o(n):o(null,r(!1,void 0)))}function f(n,e,u){return o?void i(n,function(e,c){o&&(e?(o(e),o=i=!1):t(c)&&(o(null,r(!0,n)),o=i=!1)),u()}):u()}arguments.length>3?n(e,u,f,c):(o=i,i=u,n(e,f,c))}}function Y(n,t){return t}function Z(n){return function(t,r,e){e=a(e||l),t=t||[];var u=E(t);if(0>=n)return e(null);var i=!1,o=0,c=!1;!function f(){if(i&&0>=o)return e(null);for(;n>o&&!c;){var a=u();if(null===a)return i=!0,void(0>=o&&e(null));o+=1,r(t[a],a,L(function(n){o-=1,n?(e(n),c=!0):f()}))}}()}}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]&&I(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 fn(n,t,r){return x(n,cn(t),r)}function an(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?$t(function(){r.apply(null,n)}):r.apply(null,n)}),n.apply(this,t),e=!1})}function pn(n){return!n}function yn(n,t,r,e){var u=[];n(t,function(n,t,e){r(n,function(r,i){r?e(r):(i&&u.push({index:t,value:n}),e())})},function(n){n?e(n):e(null,H(u.sort(function(n,t){return n.index-t.index}),s("value")))})}function hn(n){return function(t,r,e,u){return n(Z(r),t,e,u)}}function vn(n,t){function r(n){return n?e(n):void u(r)}var e=L(t||l),u=sn(n);r()}function mn(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=a(e||l),t=t||[];var u=y(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){return n&&n.Object===Object?n:null}function bn(n){return"symbol"==typeof n||d(n)&&sr.call(n)==ar}function kn(n){if("string"==typeof n)return n;if(null==n)return"";if(bn(n))return fr?hr.call(n):"";var t=n+"";return"0"==t&&1/n==-pr?"-0":t}function wn(n){var t=[];return kn(n).replace(vr,function(n,r,e,u){t.push(e?u.replace(mr,"$1"):r||n)}),t}function jn(n){return St(n)?n:wn(n)}function Sn(n,t){return"number"==typeof n?!0:!St(n)&&(gr.test(n)||!dr.test(n)||null!=t&&n in Object(t))}function On(n){var t=n?n.length:0;return t?n[t-1]:void 0}function En(n,t,r){var e=-1,u=n.length;0>t&&(t=-t>u?0:u+t),r=r>u?u:r,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0;for(var i=Array(u);++e<u;)i[e]=n[e+t];return i}function Ln(n,t){t=Sn(t,n)?[t+""]:jn(t);for(var r=0,e=t.length;null!=n&&e>r;)n=n[t[r++]];return r&&r==e?n:void 0}function xn(n,t,r){var e=null==n?void 0:Ln(n,t);return void 0===e?r:e}function An(n,t){return 1==t.length?n:xn(n,En(t,0,-1))}function Tn(n,t,r){if(null==n)return!1;var e=r(n,t);e||Sn(t)||(t=jn(t),n=An(n,t),null!=n&&(t=On(t),e=r(n,t)));var u=n?n.length:void 0;return e||!!u&&p(u)&&j(t,u)&&(St(n)||k(n)||b(n))}function In(n,t){return Tn(n,t,h)}function zn(n,t){var r=Object.create(null),e=Object.create(null);t=t||q;var u=o(function(u){var i=u.pop(),c=t.apply(null,u);In(r,c)?$t(function(){i.apply(null,r[c])}):In(e,c)?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 $n(n,t,r){r=r||l;var e=y(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 Mn(n,t){return $n(x,n,t)}function qn(n,t,r){return $n(Z(t),n,r)}function Bn(n,t){return N(function(t,r){n(t[0],r)},t,1)}function Fn(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,St(t)||(t=[t]),0===t.length?$t(function(){n.drain()}):void I(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(),$t(n.process)})}var i=Bn(n,t);return i.push=function(n,t,r){u(i,n,t,r)},delete i.unshift,i}function Pn(n,t,r,e){var u=kr.call(n).reverse();R(u,t,r,e)}function Un(n,t,r,e){yn(n,t,function(n,t){r(n,function(n,r){n?t(n):t(null,!r)})},e)}function Cn(n,t){return $n(A,n,t)}function Dn(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(;f.times;){var u=!(f.times-=1);c.push(r(f.task,u)),!u&&f.interval>0&&c.push(e(f.interval))}Cn(c,function(t,r){r=r[r.length-1],(n||f.callback)(r.err,r.result)})}var i=5,o=0,c=[],f={times:i,interval:o},a=arguments.length;if(1>a||a>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=a&&"function"==typeof n&&(r=t,t=n),"function"!=typeof n&&e(f,n),f.callback=r,f.task=t,f.callback?u():u}function Hn(n,t,r){function e(n,t){var r=n.criteria,e=t.criteria;return e>r?-1:r>e?1:0}Yt(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 Nn(n,t,r,e){for(var u=-1,i=xr(Lr((t-n)/(r||1)),0),o=Array(i);i--;)o[e?i:++u]=n,n+=r;return o}function Qn(n,t,r){Yt(Nn(0,n,1),t,r)}function Rn(n,t,r,e){return Zt(Nn(0,n,1),t,r,e)}function Wn(n,t,r){_t(Nn(0,n,1),t,r)}function Gn(n,t,r,e){3===arguments.length&&(e=r,r=t,t=St(n)?[]:{}),x(n,function(n,e,u){r(t,n,e,u)},function(n){e(n,t)})}function Jn(n){return function(){return(n.unmemoized||n).apply(null,arguments)}}function Kn(n,t,r){return en(function(){return!n.apply(this,arguments)},t,r)}function Vn(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=a(t||l),St(n)?n.length?void r(mn(n))():t():t(new Error("First argument to waterfall must be an array of functions"))}var Xn,Yn="[object Function]",Zn="[object GeneratorFunction]",_n=Object.prototype,nt=_n.toString,tt=NaN,rt=/^\s+|\s+$/g,et=/^[-+]0x[0-9a-f]+$/i,ut=/^0b[01]+$/i,it=/^0o[0-7]+$/i,ot=parseInt,ct=1/0,ft=1.7976931348623157e308,at="Expected a function",lt=Math.max,st="Expected a function",pt=s("length"),yt=9007199254740991,ht=Object.prototype,vt=ht.hasOwnProperty,mt=Object.getPrototypeOf,dt=Object.keys,gt="[object Arguments]",bt=Object.prototype,kt=bt.hasOwnProperty,wt=bt.toString,jt=bt.propertyIsEnumerable,St=Array.isArray,Ot="[object String]",Et=Object.prototype,Lt=Et.toString,xt=9007199254740991,At=/^(?:0|[1-9]\d*)$/,Tt=Object.prototype,It=c(x),zt="function"==typeof setImmediate&&setImmediate;Xn=zt?function(n){zt(n)}:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:function(n){setTimeout(n,0)};var $t=Xn,Mt=c(A),qt=o(function(n,t){return o(function(r){return n.apply(null,t.concat(r))})}),Bt=$(),Ft=Math.max,Pt=Array.prototype.reverse,Ut=K(J),Ct=V(J),Dt=o(function(n){var t=[null].concat(n);return function(n){return n.apply(this,t)}}),Ht=X(x,q,Y),Nt=X(_,q,Y),Qt=X(A,q,Y),Rt=nn("dir"),Wt=X(x,pn,pn),Gt=X(_,pn,pn),Jt=K(yn),Kt=hn(yn),Vt=V(yn),Xt=nn("log"),Yt=K(dn),Zt=hn(dn),_t=V(dn),nr={"function":!0,object:!0},tr=nr[typeof n]&&n&&!n.nodeType?n:null,rr=nr[typeof module]&&module&&!module.nodeType?module:null,er=gn(tr&&rr&&"object"==typeof global&&global),ur=gn(nr[typeof self]&&self),ir=gn(nr[typeof window]&&window),or=gn(nr[typeof this]&&this),cr=er||ir!==(or&&or.window)&&ir||ur||or||Function("return this")(),fr=cr.Symbol,ar="[object Symbol]",lr=Object.prototype,sr=lr.toString,pr=1/0,yr=fr?fr.prototype:void 0,hr=fr?yr.toString:void 0,vr=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g,mr=/\\(\\)?/g,dr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,gr=/^\w*$/,br="object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:$t,kr=Array.prototype.slice,wr=K(Un),jr=hn(Un),Sr=V(Un),Or=X(x,Boolean,q),Er=X(_,Boolean,q),Lr=Math.ceil,xr=Math.max,Ar={applyEach:It,applyEachSeries:Mt,apply:qt,asyncify:T,auto:D,cargo:Q,compose:G,concat:Ut,concatSeries:Ct,constant:Dt,detect:Ht,detectLimit:Nt,detectSeries:Qt,dir:Rt,doDuring:rn,doUntil:on,doWhilst:un,during:tn,each:fn,eachLimit:an,eachOf:x,eachOfLimit:_,eachOfSeries:A,eachSeries:ln,ensureAsync:sn,every:Wt,everyLimit:Gt,filter:Jt,filterLimit:Kt,filterSeries:Vt,forever:vn,iterator:mn,log:Xt,map:Yt,mapLimit:Zt,mapSeries:_t,memoize:zn,nextTick:br,parallel:Mn,parallelLimit:qn,priorityQueue:Fn,queue:Bn,reduce:R,reduceRight:Pn,reject:wr,rejectLimit:jr,rejectSeries:Sr,retry:Dn,seq:W,series:Cn,setImmediate:$t,some:Or,someLimit:Er,sortBy:Hn,times:Qn,timesLimit:Rn,timesSeries:Wn,transform:Gn,unmemoize:Jn,until:Kn,waterfall:Vn,whilst:en,all:Wt,any:Or,forEach:fn,forEachSeries:ln,forEachLimit:an,forEachOf:x,forEachOfSeries:A,forEachOfLimit:_,inject:R,foldl:R,foldr:Pn,select:Jt,selectLimit:Kt,selectSeries:Vt,wrapSync:T};n["default"]=Ar,n.applyEach=It,n.applyEachSeries=Mt,n.apply=qt,n.asyncify=T,n.auto=D,n.cargo=Q,n.compose=G,n.concat=Ut,n.concatSeries=Ct,n.constant=Dt,n.detect=Ht,n.detectLimit=Nt,n.detectSeries=Qt,n.dir=Rt,n.doDuring=rn,n.doUntil=on,n.doWhilst=un,n.during=tn,n.each=fn,n.eachLimit=an,n.eachOf=x,n.eachOfLimit=_,n.eachOfSeries=A,n.eachSeries=ln,n.ensureAsync=sn,n.every=Wt,n.everyLimit=Gt,n.filter=Jt,n.filterLimit=Kt,n.filterSeries=Vt,n.forever=vn,n.iterator=mn,n.log=Xt,n.map=Yt,n.mapLimit=Zt,n.mapSeries=_t,n.memoize=zn,n.nextTick=br,n.parallel=Mn,n.parallelLimit=qn,n.priorityQueue=Fn,n.queue=Bn,n.reduce=R,n.reduceRight=Pn,n.reject=wr,n.rejectLimit=jr,n.rejectSeries=Sr,n.retry=Dn,n.seq=W,n.series=Cn,n.setImmediate=$t,n.some=Or,n.someLimit=Er,n.sortBy=Hn,n.times=Qn,n.timesLimit=Rn,n.timesSeries=Wn,n.transform=Gn,n.unmemoize=Jn,n.until=Kn,n.waterfall=Vn,n.whilst=en,n.all=Wt,n.any=Or,n.forEach=fn,n.forEachSeries=ln,n.forEachLimit=an,n.forEachOf=x,n.forEachOfSeries=A,n.forEachOfLimit=_,n.inject=R,n.foldl=R,n.foldr=Pn,n.select=Jt,n.selectLimit=Kt,n.selectSeries=Vt,n.wrapSync=T});
//# sourceMappingURL=dist/async.min.map \ No newline at end of file
diff --git a/dist/async.min.map b/dist/async.min.map
index 90771f3..9156fcc 100644
--- a/dist/async.min.map
+++ b/dist/async.min.map
@@ -1 +1 @@
-{"version":3,"file":"dist/async.min.js","sources":["dist/async.js"],"names":["noop","identity","v","toBool","notId","only_once","fn","Error","apply","this","arguments","_once","_isArrayLike","arr","_isArray","length","_arrayEach","iterator","index","_map","result","Array","_range","count","i","_reduce","memo","x","a","_forEachOf","object","_keys","key","_indexOf","item","_keyIterator","coll","len","keys","_restParam","func","startIndex","Math","max","rest","call","_withoutIndex","value","callback","_eachOfLimit","limit","obj","nextKey","done","running","errored","replenish","err","doParallel","async","eachOf","doParallelLimit","doSeries","eachOfSeries","_asyncMap","eachfn","results","_filter","push","sort","b","_reject","cb","_createTester","check","getResult","iteratee","_","_findGetResult","_parallel","tasks","task","args","_concat","y","concat","_queue","worker","concurrency","payload","_insert","q","data","pos","started","idle","setImmediate","drain","unshift","saturated","process","_next","workers","removed","workersList","splice","empty","paused","kill","pause","resume","resumeCount","min","w","_console_fn","name","console","error","_times","mapper","_applyEach","fns","go","that","pop","ensureAsync","innerArgs","sync","previous_async","root","self","global","noConflict","_toString","Object","prototype","toString","isArray","_isObject","type","k","hasOwnProperty","_setImmediate","_delay","setTimeout","nextTick","forEach","each","forEachSeries","eachSeries","forEachLimit","eachLimit","forEachOf","completed","iter","forEachOfSeries","iterate","forEachOfLimit","eachOfLimit","map","mapSeries","mapLimit","inject","foldl","reduce","foldr","reduceRight","reversed","reverse","transform","select","filter","selectLimit","filterLimit","selectSeries","filterSeries","reject","rejectLimit","rejectSeries","any","some","someLimit","all","every","everyLimit","detect","detectSeries","detectLimit","sortBy","comparator","left","right","criteria","auto","addListener","listeners","removeListener","idx","taskComplete","remainingTasks","slice","runningTasks","hasError","ready","requires","listener","taskCallback","dep","safeResults","val","rkey","retry","times","parseTimes","acc","t","parseInt","DEFAULT_TIMES","interval","DEFAULT_INTERVAL","wrappedTask","wrappedCallback","wrappedResults","retryAttempt","finalAttempt","seriesCallback","retryInterval","opts","attempts","series","waterfall","wrapIterator","next","parallel","parallelLimit","makeCallback","callArgs","concatSeries","whilst","test","doWhilst","calls","until","doUntil","during","truth","doDuring","queue","items","priorityQueue","_compareTasks","priority","_binarySearch","sequence","compare","beg","end","mid","cargo","log","dir","memoize","hasher","queues","memoized","l","unmemoized","unmemoize","timesSeries","timesLimit","seq","newargs","nextargs","compose","applyEach","applyEachSeries","forever","constant","values","wrapSync","asyncify","e","then","message","module","exports","define","amd"],"mappings":"CAOC,WAGG,QAASA,MACT,QAASC,GAASC,GACd,MAAOA,GAEX,QAASC,GAAOD,GACZ,QA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7K,EAAMkE,YAAcA,EAEpBlE,EAAM0N,SAAW9O,EAAW,SAAS+O,GACjC,GAAIpM,IAAQ,MAAMG,OAAOiM,EACzB,OAAO,UAAUtO,GACb,MAAOA,GAASxC,MAAMC,KAAMyE,MAIpCvB,EAAM4N,SACN5N,EAAM6N,SAAW,SAAkBhP,GAC/B,MAAOD,GAAW,SAAU2C,GACxB,GACI9D,GADA4B,EAAWkC,EAAK0C,KAEpB,KACIxG,EAASoB,EAAKhC,MAAMC,KAAMyE,GAC5B,MAAOuM,GACL,MAAOzO,GAASyO,GAGhB/I,EAAUtH,IAAkC,kBAAhBA,GAAOsQ,KACnCtQ,EAAOsQ,KAAK,SAAS3O,GACjBC,EAAS,KAAMD,KAChB,SAAS,SAASU,GACjBT,EAASS,EAAIkO,QAAUlO,EAAM,GAAIlD,OAAMkD,MAG3CT,EAAS,KAAM5B,MAML,gBAAXwQ,SAAuBA,OAAOC,QACrCD,OAAOC,QAAUlO,EAGM,kBAAXmO,SAAyBA,OAAOC,IAC5CD,UAAW,WACP,MAAOnO,KAKXsE,EAAKtE,MAAQA"} \ No newline at end of file
+{"version":3,"file":"build/dist/async.min.js","sources":["build/dist/async.js"],"names":["global","factory","exports","module","define","amd","async","this","apply$1","func","thisArg","args","length","call","apply","isObject","value","type","isFunction","tag","objectToString$2","funcTag","genTag","toNumber","other","valueOf","replace","reTrim","isBinary","reIsBinary","test","reIsOctal","freeParseInt","slice","reIsBadHex","NAN","toInteger","INFINITY","sign","MAX_INTEGER","remainder","rest","start","TypeError","FUNC_ERROR_TEXT","nativeMax","undefined","arguments","index","array","Array","otherArgs","applyEach$1","eachfn","fns","go","that","callback","pop","fn","_","cb","concat","before","n","result","FUNC_ERROR_TEXT$1","once","noop","baseProperty","key","object","isLength","MAX_SAFE_INTEGER$1","isArrayLike","getLength","baseHas","hasOwnProperty","getPrototypeOf","baseKeys","nativeKeys","Object","baseTimes","iteratee","isObjectLike","isArrayLikeObject","isArguments","hasOwnProperty$1","propertyIsEnumerable","objectToString","argsTag","isString","isArray","objectToString$1","stringTag","indexKeys","String","isIndex","reIsUint","MAX_SAFE_INTEGER","isPrototype","Ctor","constructor","proto","prototype","objectProto$1","keys","isProto","indexes","skipIndexes","push","keyIterator","coll","len","i","okeys","onlyOnce","Error","eachOf","iterator","done","err","completed","iter","eachOfSeries","obj","iterate","sync","nextKey","setImmediate$1","asyncify","e","then","message","arrayEach","arrayEvery","predicate","createBaseFor","fromRight","keysFunc","iterable","props","baseForOwn","baseFor","identity","toFunction","forOwn","indexOfNaN","fromIndex","baseIndexOf","indexOf","nativeMax$1","auto","tasks","concurrency","addListener","listeners","unshift","removeListener","idx","splice","taskComplete","remainingTasks","keys$$","results","runningTasks","hasError","k","ready","requires","x","listener","task","taskCallback","dep","safeResults","val","rkey","join","arrayMap","queue$1","worker","payload","_insert","q","data","pos","started","idle","drain","item","saturated","process","_next","workers","removed","workersList","empty","paused","kill","running","pause","resume","resumeCount","Math","min","w","cargo","reduce","arr","memo","v","seq","newargs","nextargs","compose","reverse","concat$1","y","doParallel","doSeries","_createTester","check","getResult","limit","_findGetResult","_eachOfLimit","errored","replenish","eachOfLimit","consoleFunc","name","console","error","during","next","truth","doDuring","calls","whilst","doWhilst","doUntil","_withoutIndex","each","eachLimit","eachSeries","ensureAsync","innerArgs","notId","_filter","sort","a","b","doParallelLimit","forever","makeCallback","_asyncMap","checkGlobal","isSymbol","objectToString$3","symbolTag","toString","Symbol","symbolToString","INFINITY$1","stringToPath","string","rePropName","match","number","quote","reEscapeChar","baseToPath","isKey","reIsPlainProp","reIsDeepProp","last","baseSlice","end","baseGet","path","get","defaultValue","parent","hasPath","hasFunc","has","memoize","hasher","create","queues","memoized","l","unmemoized","_parallel","parallel","parallelLimit","queue","items","priorityQueue","_compareTasks","priority","_binarySearch","sequence","compare","beg","mid","reduceRight","reversed","reject$1","series","retry","times","parseTimes","acc","t","parseInt","DEFAULT_TIMES","interval","DEFAULT_INTERVAL","wrappedTask","wrappedCallback","wrappedResults","retryAttempt","finalAttempt","seriesCallback","retryInterval","setTimeout","opts","attempts","sortBy","comparator","left","right","criteria","map","baseRange","step","nativeMax$2","nativeCeil","count","timeLimit","mapLimit","timesSeries","mapSeries","transform","unmemoize","until","waterfall","wrapIterator","_delay","objectProto$4","max","objectProto","objectProto$2","objectProto$3","applyEach","_setImmediate","setImmediate","nextTick","applyEachSeries","callArgs","concatSeries","constant","values","detect","detectLimit","detectSeries","dir","every","everyLimit","filter","filterLimit","filterSeries","log","objectTypes","function","freeExports","nodeType","freeModule","freeGlobal","freeSelf","self","freeWindow","window","thisGlobal","root","Function","objectProto$5","symbolProto","nexTick","reject","rejectLimit","rejectSeries","some","Boolean","someLimit","ceil","timesLimit","all","any","forEach","forEachSeries","forEachLimit","forEachOf","forEachOfSeries","forEachOfLimit","inject","foldl","foldr","select","selectLimit","selectSeries","wrapSync"],"mappings":"CAAC,SAAUA,EAAQC,GACE,gBAAZC,UAA0C,mBAAXC,QAAyBF,EAAQC,SACrD,kBAAXE,SAAyBA,OAAOC,IAAMD,QAAQ,WAAYH,GAChEA,EAASD,EAAOM,WACjBC,KAAM,SAAUL,GAAW,YAY3B,SAASM,GAAQC,EAAMC,EAASC,GAC9B,GAAIC,GAASD,EAAKC,MAClB,QAAQA,GACN,IAAK,GAAG,MAAOH,GAAKI,KAAKH,EACzB,KAAK,GAAG,MAAOD,GAAKI,KAAKH,EAASC,EAAK,GACvC,KAAK,GAAG,MAAOF,GAAKI,KAAKH,EAASC,EAAK,GAAIA,EAAK,GAChD,KAAK,GAAG,MAAOF,GAAKI,KAAKH,EAASC,EAAK,GAAIA,EAAK,GAAIA,EAAK,IAE3D,MAAOF,GAAKK,MAAMJ,EAASC,GA0B7B,QAASI,GAASC,GAChB,GAAIC,SAAcD,EAClB,SAASA,IAAkB,UAARC,GAA4B,YAARA,GA8BzC,QAASC,GAAWF,GAIlB,GAAIG,GAAMJ,EAASC,GAASI,GAAiBP,KAAKG,GAAS,EAC3D,OAAOG,IAAOE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6Y,IAAM9B,GACd/W,EAAQ8Y,IAAMN,GACdxY,EAAQ+Y,QAAU9J,GAClBjP,EAAQgZ,cAAgB7J,GACxBnP,EAAQiZ,aAAe/J,GACvBlP,EAAQkZ,UAAY9R,EACpBpH,EAAQmZ,gBAAkBzR,EAC1B1H,EAAQoZ,eAAiBjL,EACzBnO,EAAQqZ,OAASvM,EACjB9M,EAAQsZ,MAAQxM,EAChB9M,EAAQuZ,MAAQtG,GAChBjT,EAAQwZ,OAASvC,GACjBjX,EAAQyZ,YAAcvC,GACtBlX,EAAQ0Z,aAAevC,GACvBnX,EAAQ2Z,SAAW3R"} \ No newline at end of file
diff --git a/gulpfile.js b/gulpfile.js
new file mode 100644
index 0000000..fbc58a1
--- /dev/null
+++ b/gulpfile.js
@@ -0,0 +1,89 @@
+'use strict';
+// This is used to generate individual packages for each async method
+
+var gulp = require('gulp');
+var path = require('path');
+var fs = require('fs-extra');
+var pkg = require('./package.json');
+var jsonFuture = require('json-future');
+var template = require('lodash.template');
+
+var moduleDeps = JSON.parse(template(fs.readFileSync('./support/dependencies.json').toString())({
+ version: pkg.version}
+ ));
+
+var MODULES_PATH = './lib/';
+
+function getFolders(dir) {
+ return fs.readdirSync(dir)
+ .filter(function(file) {
+ return fs.statSync(path.join(dir, file)).isDirectory();
+ });
+}
+
+function generatePackage(name) {
+ function generateKeywords(name) {
+ var keywords = [
+ 'async',
+ 'async-modularized'
+ ];
+
+ keywords.push(name);
+ return keywords;
+ }
+
+ function generateDefaultFields(name) {
+ var ORIGINAL_FIELDS = [
+ 'author',
+ 'version',
+ 'repository',
+ 'license'
+ ];
+
+ var structure = {
+ name: 'async.' + name,
+ description: 'async ' + name + 'method as module.',
+ main: './index.js',
+ repository: "async-js/async." + name
+ };
+
+ ORIGINAL_FIELDS.forEach(function(field) {
+ structure[field] = pkg[field];
+ });
+
+ if (Object.keys(moduleDeps[name]).length > 0)
+ structure.dependencies = moduleDeps[name];
+
+ return structure;
+ }
+
+ var modulePackage = generateDefaultFields(name);
+ modulePackage.keywords = generateKeywords(name);
+ return modulePackage;
+}
+
+function generateReadme(name, dist) {
+ var filepath = path.resolve('support/module_template.md');
+ var tpl = fs.readFileSync(filepath).toString();
+ tpl = template(tpl)({name: name});
+ fs.writeFileSync(dist, tpl);
+}
+
+function copyMetaFiles(dist) {
+ var files = ['.editorconfig', '.jscsrc', '.jshintrc', '.gitignore'];
+
+ files.forEach(function(file) {
+ var metafile = path.resolve(file);
+ var distFile = path.resolve(dist, file);
+ fs.copySync(metafile, distFile);
+ });
+}
+
+gulp.task('package', function() {
+ return getFolders(MODULES_PATH).map(function(module) {
+ var dist = path.resolve(MODULES_PATH, module);
+ jsonFuture.save(path.resolve(dist, 'package.json'), generatePackage(module));
+ generateReadme(module, path.resolve(dist, 'README.md'));
+ copyMetaFiles(dist);
+ });
+});
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..031f690
--- /dev/null
+++ b/index.js
@@ -0,0 +1,3 @@
+// This is not the main file in the npm package, but here so we can use github
+// tarballs as packages when necessary.
+module.exports = require("./build/");
diff --git a/karma.conf.js b/karma.conf.js
index 9e048c3..0e90828 100644
--- a/karma.conf.js
+++ b/karma.conf.js
@@ -1,12 +1,17 @@
-module.exports = function (config) {
- config.set({
- browsers: ['Firefox'],
- files: ['mocha_test/*.js'],
- frameworks: ['browserify', 'mocha'],
- preprocessors: {
- 'mocha_test/*.js': ['browserify']
- },
- reporters: ['mocha'],
- singleRun: true
- });
-}
+module.exports = function(config) {
+ config.set({
+ browsers: ['Firefox'],
+ files: ['mocha_test/*.js'],
+ frameworks: ['browserify', 'mocha'],
+ preprocessors: {
+ 'mocha_test/*.js': ['browserify']
+ },
+ reporters: ['mocha'],
+ singleRun: true,
+
+ browserify: {
+ debug: true,
+ transform: ['babelify']
+ }
+ });
+};
diff --git a/lib/apply.js b/lib/apply.js
new file mode 100644
index 0000000..76b5602
--- /dev/null
+++ b/lib/apply.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import rest from 'lodash/rest';
+
+export default rest(function(fn, args) {
+ return rest(function(callArgs) {
+ return fn.apply(null, args.concat(callArgs));
+ });
+});
diff --git a/lib/applyEach.js b/lib/applyEach.js
new file mode 100644
index 0000000..2c5f001
--- /dev/null
+++ b/lib/applyEach.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import applyEach from './internal/applyEach';
+import eachOf from './eachOf';
+
+export default applyEach(eachOf);
diff --git a/lib/applyEachSeries.js b/lib/applyEachSeries.js
new file mode 100644
index 0000000..e917618
--- /dev/null
+++ b/lib/applyEachSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import applyEach from './internal/applyEach';
+import eachOfSeries from './eachOfSeries';
+
+export default applyEach(eachOfSeries);
diff --git a/lib/async.js b/lib/async.js
deleted file mode 100755
index f3450ce..0000000
--- a/lib/async.js
+++ /dev/null
@@ -1,1310 +0,0 @@
-/*!
- * async
- * https://github.com/caolan/async
- *
- * Copyright 2010-2014 Caolan McMahon
- * Released under the MIT license
- */
-(function () {
-
- var async = {};
- function noop() {}
- function identity(v) {
- return v;
- }
- function toBool(v) {
- return !!v;
- }
- function notId(v) {
- return !v;
- }
-
- // global on the server, window in the browser
- var previous_async;
-
- // Establish the root object, `window` (`self`) in the browser, `global`
- // on the server, or `this` in some virtual machines. We use `self`
- // instead of `window` for `WebWorker` support.
- var root = typeof self === 'object' && self.self === self && self ||
- typeof global === 'object' && global.global === global && global ||
- this;
-
- if (root != null) {
- previous_async = root.async;
- }
-
- async.noConflict = function () {
- root.async = previous_async;
- return async;
- };
-
- function only_once(fn) {
- return function() {
- if (fn === null) throw new Error("Callback was already called.");
- fn.apply(this, arguments);
- fn = null;
- };
- }
-
- function _once(fn) {
- return function() {
- if (fn === null) return;
- fn.apply(this, arguments);
- fn = null;
- };
- }
-
- //// cross-browser compatiblity functions ////
-
- var _toString = Object.prototype.toString;
-
- var _isArray = Array.isArray || function (obj) {
- return _toString.call(obj) === '[object Array]';
- };
-
- // Ported from underscore.js isObject
- var _isObject = function(obj) {
- var type = typeof obj;
- return type === 'function' || type === 'object' && !!obj;
- };
-
- function _isArrayLike(arr) {
- return _isArray(arr) || (
- // has a positive integer length property
- typeof arr.length === "number" &&
- arr.length >= 0 &&
- arr.length % 1 === 0
- );
- }
-
- function _arrayEach(arr, iterator) {
- var index = -1,
- length = arr.length;
-
- while (++index < length) {
- iterator(arr[index], index, arr);
- }
- }
-
- function _map(arr, iterator) {
- var index = -1,
- length = arr.length,
- result = Array(length);
-
- while (++index < length) {
- result[index] = iterator(arr[index], index, arr);
- }
- return result;
- }
-
- function _range(count) {
- return _map(Array(count), function (v, i) { return i; });
- }
-
- function _reduce(arr, iterator, memo) {
- _arrayEach(arr, function (x, i, a) {
- memo = iterator(memo, x, i, a);
- });
- return memo;
- }
-
- function _forEachOf(object, iterator) {
- _arrayEach(_keys(object), function (key) {
- iterator(object[key], key);
- });
- }
-
- function _indexOf(arr, item) {
- for (var i = 0; i < arr.length; i++) {
- if (arr[i] === item) return i;
- }
- return -1;
- }
-
- var _keys = Object.keys || function (obj) {
- var keys = [];
- for (var k in obj) {
- if (obj.hasOwnProperty(k)) {
- keys.push(k);
- }
- }
- return keys;
- };
-
- function _keyIterator(coll) {
- var i = -1;
- var len;
- var keys;
- if (_isArrayLike(coll)) {
- len = coll.length;
- return function next() {
- i++;
- return i < len ? i : null;
- };
- } else {
- keys = _keys(coll);
- len = keys.length;
- return function next() {
- i++;
- return i < len ? keys[i] : null;
- };
- }
- }
-
- // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
- // This accumulates the arguments passed into an array, after a given index.
- // From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
- function _restParam(func, startIndex) {
- startIndex = startIndex == null ? func.length - 1 : +startIndex;
- return function() {
- var length = Math.max(arguments.length - startIndex, 0);
- var rest = Array(length);
- for (var index = 0; index < length; index++) {
- rest[index] = arguments[index + startIndex];
- }
- switch (startIndex) {
- case 0: return func.call(this, rest);
- case 1: return func.call(this, arguments[0], rest);
- }
- // Currently unused but handle cases outside of the switch statement:
- // var args = Array(startIndex + 1);
- // for (index = 0; index < startIndex; index++) {
- // args[index] = arguments[index];
- // }
- // args[startIndex] = rest;
- // return func.apply(this, args);
- };
- }
-
- function _withoutIndex(iterator) {
- return function (value, index, callback) {
- return iterator(value, callback);
- };
- }
-
- //// exported async module functions ////
-
- //// nextTick implementation with browser-compatible fallback ////
-
- // capture the global reference to guard against fakeTimer mocks
- var _setImmediate = typeof setImmediate === 'function' && setImmediate;
-
- var _delay = _setImmediate ? function(fn) {
- // not a direct alias for IE10 compatibility
- _setImmediate(fn);
- } : function(fn) {
- setTimeout(fn, 0);
- };
-
- if (typeof process === 'object' && typeof process.nextTick === 'function') {
- async.nextTick = process.nextTick;
- } else {
- async.nextTick = _delay;
- }
- async.setImmediate = _setImmediate ? _delay : async.nextTick;
-
-
- async.forEach =
- async.each = function (arr, iterator, callback) {
- return async.eachOf(arr, _withoutIndex(iterator), callback);
- };
-
- async.forEachSeries =
- async.eachSeries = function (arr, iterator, callback) {
- return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
- };
-
-
- async.forEachLimit =
- async.eachLimit = function (arr, limit, iterator, callback) {
- return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
- };
-
- async.forEachOf =
- async.eachOf = function (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, only_once(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);
- }
- }
- };
-
- async.forEachOfSeries =
- async.eachOfSeries = function (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, only_once(function (err) {
- if (err) {
- callback(err);
- }
- else {
- key = nextKey();
- if (key === null) {
- return callback(null);
- } else {
- if (sync) {
- async.setImmediate(iterate);
- } else {
- iterate();
- }
- }
- }
- }));
- sync = false;
- }
- iterate();
- };
-
-
-
- async.forEachOfLimit =
- async.eachOfLimit = function (obj, limit, iterator, callback) {
- _eachOfLimit(limit)(obj, iterator, callback);
- };
-
- 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, only_once(function (err) {
- running -= 1;
- if (err) {
- callback(err);
- errored = true;
- }
- else {
- replenish();
- }
- }));
- }
- })();
- };
- }
-
-
- function doParallel(fn) {
- return function (obj, iterator, callback) {
- return fn(async.eachOf, obj, iterator, callback);
- };
- }
- function doParallelLimit(fn) {
- return function (obj, limit, iterator, callback) {
- return fn(_eachOfLimit(limit), obj, iterator, callback);
- };
- }
- function doSeries(fn) {
- return function (obj, iterator, callback) {
- return fn(async.eachOfSeries, obj, iterator, callback);
- };
- }
-
- 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);
- });
- }
-
- async.map = doParallel(_asyncMap);
- async.mapSeries = doSeries(_asyncMap);
- async.mapLimit = doParallelLimit(_asyncMap);
-
- // reduce only has a series version, as doing reduce in parallel won't
- // work in many situations.
- async.inject =
- async.foldl =
- async.reduce = function (arr, memo, iterator, callback) {
- async.eachOfSeries(arr, function (x, i, callback) {
- iterator(memo, x, function (err, v) {
- memo = v;
- callback(err);
- });
- }, function (err) {
- callback(err, memo);
- });
- };
-
- async.foldr =
- async.reduceRight = function (arr, memo, iterator, callback) {
- var reversed = _map(arr, identity).reverse();
- async.reduce(reversed, memo, iterator, callback);
- };
-
- async.transform = function (arr, memo, iterator, callback) {
- if (arguments.length === 3) {
- callback = iterator;
- iterator = memo;
- memo = _isArray(arr) ? [] : {};
- }
-
- async.eachOf(arr, function(v, k, cb) {
- iterator(memo, v, k, cb);
- }, function(err) {
- callback(err, memo);
- });
- };
-
- function _filter(eachfn, arr, iterator, callback) {
- var results = [];
- eachfn(arr, function (x, index, callback) {
- iterator(x, function (v) {
- if (v) {
- results.push({index: index, value: x});
- }
- callback();
- });
- }, function () {
- callback(_map(results.sort(function (a, b) {
- return a.index - b.index;
- }), function (x) {
- return x.value;
- }));
- });
- }
-
- async.select =
- async.filter = doParallel(_filter);
-
- async.selectLimit =
- async.filterLimit = doParallelLimit(_filter);
-
- async.selectSeries =
- async.filterSeries = doSeries(_filter);
-
- function _reject(eachfn, arr, iterator, callback) {
- _filter(eachfn, arr, function(value, cb) {
- iterator(value, function(v) {
- cb(!v);
- });
- }, callback);
- }
- async.reject = doParallel(_reject);
- async.rejectLimit = doParallelLimit(_reject);
- async.rejectSeries = doSeries(_reject);
-
- 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);
- }
- };
- }
-
- async.any =
- async.some = _createTester(async.eachOf, toBool, identity);
-
- async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
-
- async.all =
- async.every = _createTester(async.eachOf, notId, notId);
-
- async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
-
- function _findGetResult(v, x) {
- return x;
- }
- async.detect = _createTester(async.eachOf, identity, _findGetResult);
- async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
- async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
-
- async.sortBy = function (arr, iterator, callback) {
- async.map(arr, function (x, callback) {
- iterator(x, function (err, criteria) {
- if (err) {
- callback(err);
- }
- else {
- callback(null, {value: x, criteria: criteria});
- }
- });
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
- else {
- callback(null, _map(results.sort(comparator), function (x) {
- return x.value;
- }));
- }
-
- });
-
- function comparator(left, right) {
- var a = left.criteria, b = right.criteria;
- return a < b ? -1 : a > b ? 1 : 0;
- }
- };
-
- async.auto = 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 = _keys(tasks);
- var remainingTasks = keys.length;
- if (!remainingTasks) {
- return callback(null);
- }
- if (!concurrency) {
- concurrency = remainingTasks;
- }
-
- var results = {};
- var runningTasks = 0;
-
- var hasError = false;
-
- 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(0), function (fn) {
- fn();
- });
- }
-
- addListener(function () {
- if (!remainingTasks) {
- callback(null, results);
- }
- });
-
- _arrayEach(keys, function (k) {
- if (hasError) return;
- var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
- var taskCallback = _restParam(function(err, args) {
- runningTasks--;
- if (args.length <= 1) {
- args = args[0];
- }
- if (err) {
- var safeResults = {};
- _forEachOf(results, function(val, rkey) {
- safeResults[rkey] = val;
- });
- safeResults[k] = args;
- hasError = true;
-
- callback(err, safeResults);
- }
- else {
- results[k] = args;
- async.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 in ' + requires.join(', '));
- }
- if (_isArray(dep) && _indexOf(dep, k) >= 0) {
- throw new Error('Has cyclic dependencies');
- }
- }
- function ready() {
- return runningTasks < concurrency && _reduce(requires, function (a, x) {
- return (a && results.hasOwnProperty(x));
- }, true) && !results.hasOwnProperty(k);
- }
- 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);
- }
- }
- });
- };
-
- var _funcParamRegEx = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
- var _funcParamNames = function(func) {
- var result = func.toString().match(_funcParamRegEx)[1].split(',');
-
- for (var i = 0, e = result.length; i != e; ++i) {
- result[i] = result[i].trim();
- }
-
- return result;
- };
-
- async.autoInject = function(tasks, concurrency, callback) {
- if (typeof arguments[1] === 'function') {
- // concurrency is optional, shift the args.
- callback = concurrency;
- concurrency = null;
- }
- var injTasks = {};
- for (var i in tasks) {
- injTasks[i] = (function(val) {
- if (!(val instanceof Function)) {
- return val;
- }
-
- var params = _funcParamNames(val);
- if (params.length < 2) {
- return val;
- }
-
- params.pop();
-
- return params.concat(function(cb, results) {
- val.apply(null, _map(params, function(a) { return results[a]; }).concat(cb));
- });
-
- return params;
- })(tasks[i]);
- }
-
- return this.auto(
- injTasks,
- concurrency,
- callback && function(err, results) {
- callback.apply(null, [err].concat(_map(_funcParamNames(callback).slice(1), function(a) { return results[a]; })));
- }
- );
- };
-
- async.retry = function(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));
- }
- }
-
- async.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;
- };
-
- async.waterfall = function (tasks, callback) {
- callback = _once(callback || noop);
- if (!_isArray(tasks)) {
- var err = new Error('First argument to waterfall must be an array of functions');
- return callback(err);
- }
- if (!tasks.length) {
- return callback();
- }
- function wrapIterator(iterator) {
- return _restParam(function (err, args) {
- if (err) {
- callback.apply(null, [err].concat(args));
- }
- else {
- var next = iterator.next();
- if (next) {
- args.push(wrapIterator(next));
- }
- else {
- args.push(callback);
- }
- ensureAsync(iterator).apply(null, args);
- }
- });
- }
- wrapIterator(async.iterator(tasks))();
- };
-
- function _parallel(eachfn, tasks, callback) {
- callback = callback || noop;
- var results = _isArrayLike(tasks) ? [] : {};
-
- eachfn(tasks, function (task, key, callback) {
- task(_restParam(function (err, args) {
- if (args.length <= 1) {
- args = args[0];
- }
- results[key] = args;
- callback(err);
- }));
- }, function (err) {
- callback(err, results);
- });
- }
-
- async.parallel = function (tasks, callback) {
- _parallel(async.eachOf, tasks, callback);
- };
-
- async.parallelLimit = function(tasks, limit, callback) {
- _parallel(_eachOfLimit(limit), tasks, callback);
- };
-
- async.series = function(tasks, callback) {
- _parallel(async.eachOfSeries, tasks, callback);
- };
-
- async.iterator = 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);
- };
-
- async.apply = _restParam(function (fn, args) {
- return _restParam(function (callArgs) {
- return fn.apply(
- null, args.concat(callArgs)
- );
- });
- });
-
- 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);
- });
- }
- async.concat = doParallel(_concat);
- async.concatSeries = doSeries(_concat);
-
- async.whilst = function (test, iterator, callback) {
- callback = callback || noop;
- if (test()) {
- var next = _restParam(function(err, args) {
- if (err) {
- callback(err);
- } else if (test.apply(this, args)) {
- iterator(next);
- } else {
- callback.apply(null, [null].concat(args));
- }
- });
- iterator(next);
- } else {
- callback(null);
- }
- };
-
- async.doWhilst = function (iterator, test, callback) {
- var calls = 0;
- return async.whilst(function() {
- return ++calls <= 1 || test.apply(this, arguments);
- }, iterator, callback);
- };
-
- async.until = function (test, iterator, callback) {
- return async.whilst(function() {
- return !test.apply(this, arguments);
- }, iterator, callback);
- };
-
- async.doUntil = function (iterator, test, callback) {
- return async.doWhilst(iterator, function() {
- return !test.apply(this, arguments);
- }, callback);
- };
-
- async.during = function (test, iterator, callback) {
- callback = callback || noop;
-
- var next = _restParam(function(err, args) {
- if (err) {
- callback(err);
- } else {
- args.push(check);
- test.apply(this, args);
- }
- });
-
- var check = function(err, truth) {
- if (err) {
- callback(err);
- } else if (truth) {
- iterator(next);
- } else {
- callback(null);
- }
- };
-
- test(check);
- };
-
- async.doDuring = function (iterator, test, callback) {
- var calls = 0;
- async.during(function(next) {
- if (calls++ < 1) {
- next(null, true);
- } else {
- test.apply(this, arguments);
- }
- }, iterator, callback);
- };
-
- 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 async.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();
- }
- });
- async.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 = _map(tasks, function (task) {
- return task.data;
- });
-
- if (q.tasks.length === 0) {
- q.empty();
- }
- workers += 1;
- workersList.push(tasks[0]);
- var cb = only_once(_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++) {
- async.setImmediate(q.process);
- }
- }
- };
- return q;
- }
-
- async.queue = function (worker, concurrency) {
- var q = _queue(function (items, cb) {
- worker(items[0], cb);
- }, concurrency, 1);
-
- return q;
- };
-
- async.priorityQueue = 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 async.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();
- }
- async.setImmediate(q.process);
- });
- }
-
- // Start with a normal queue
- var q = async.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;
- };
-
- async.cargo = function (worker, payload) {
- return _queue(worker, 1, payload);
- };
-
- function _console_fn(name) {
- return _restParam(function (fn, args) {
- fn.apply(null, args.concat([_restParam(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);
- });
- }
- }
- })]));
- });
- }
- async.log = _console_fn('log');
- async.dir = _console_fn('dir');
- /*async.info = _console_fn('info');
- async.warn = _console_fn('warn');
- async.error = _console_fn('error');*/
-
- async.memoize = function (fn, hasher) {
- var memo = {};
- var queues = {};
- hasher = hasher || identity;
- var memoized = _restParam(function memoized(args) {
- var callback = args.pop();
- var key = hasher.apply(null, args);
- if (key in memo) {
- async.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([_restParam(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;
- };
-
- async.unmemoize = function (fn) {
- return function () {
- return (fn.unmemoized || fn).apply(null, arguments);
- };
- };
-
- function _times(mapper) {
- return function (count, iterator, callback) {
- mapper(_range(count), iterator, callback);
- };
- }
-
- async.times = _times(async.map);
- async.timesSeries = _times(async.mapSeries);
- async.timesLimit = function (count, limit, iterator, callback) {
- return async.mapLimit(_range(count), limit, iterator, callback);
- };
-
- async.seq = function (/* functions... */) {
- var fns = arguments;
- return _restParam(function (args) {
- var that = this;
-
- var callback = args[args.length - 1];
- if (typeof callback == 'function') {
- args.pop();
- } else {
- callback = noop;
- }
-
- async.reduce(fns, args, function (newargs, fn, cb) {
- fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
- cb(err, nextargs);
- })]));
- },
- function (err, results) {
- callback.apply(that, [err].concat(results));
- });
- });
- };
-
- async.compose = function (/* functions... */) {
- return async.seq.apply(null, Array.prototype.reverse.call(arguments));
- };
-
-
- function _applyEach(eachfn) {
- return _restParam(function(fns, args) {
- var go = _restParam(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;
- }
- });
- }
-
- async.applyEach = _applyEach(async.eachOf);
- async.applyEachSeries = _applyEach(async.eachOfSeries);
-
-
- async.forever = function (fn, callback) {
- var done = only_once(callback || noop);
- var task = ensureAsync(fn);
- function next(err) {
- if (err) {
- return done(err);
- }
- task(next);
- }
- next();
- };
-
- function ensureAsync(fn) {
- return _restParam(function (args) {
- var callback = args.pop();
- args.push(function () {
- var innerArgs = arguments;
- if (sync) {
- async.setImmediate(function () {
- callback.apply(null, innerArgs);
- });
- } else {
- callback.apply(null, innerArgs);
- }
- });
- var sync = true;
- fn.apply(this, args);
- sync = false;
- });
- }
-
- async.ensureAsync = ensureAsync;
-
- async.constant = _restParam(function(values) {
- var args = [null].concat(values);
- return function (callback) {
- return callback.apply(this, args);
- };
- });
-
- async.wrapSync =
- async.asyncify = function asyncify(func) {
- return _restParam(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);
- }
- });
- };
-
- // Node.js
- if (typeof module === 'object' && module.exports) {
- module.exports = async;
- }
- // AMD / RequireJS
- else if (typeof define === 'function' && define.amd) {
- define([], function () {
- return async;
- });
- }
- // included directly via <script> tag
- else {
- root.async = async;
- }
-
-}());
diff --git a/lib/asyncify.js b/lib/asyncify.js
new file mode 100644
index 0000000..f9f00e1
--- /dev/null
+++ b/lib/asyncify.js
@@ -0,0 +1,26 @@
+'use strict';
+
+import isObject from 'lodash/isObject';
+import rest from 'lodash/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/lib/auto.js b/lib/auto.js
new file mode 100644
index 0000000..0e9d108
--- /dev/null
+++ b/lib/auto.js
@@ -0,0 +1,135 @@
+'use strict';
+
+import arrayEach from 'lodash/_arrayEach';
+import arrayEvery from 'lodash/_arrayEvery';
+import baseHas from 'lodash/_baseHas';
+import forOwn from 'lodash/forOwn';
+import indexOf from 'lodash/indexOf';
+import isArray from 'lodash/isArray';
+import okeys from 'lodash/keys';
+import noop from 'lodash/noop';
+import once from 'lodash/once';
+import rest from 'lodash/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 hasError = false;
+
+ 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) {
+ if (hasError) return;
+ 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;
+ hasError = true;
+ listeners = [];
+
+ callback(err, safeResults);
+ }
+ else {
+ results[k] = args;
+ setImmediate(taskComplete);
+ }
+ });
+
+ var requires = task.slice(0, task.length - 1);
+
+ checkForDeadlocks();
+
+ if (ready()) {
+ startNext();
+ } else {
+ addListener(listener);
+ }
+
+ function checkForDeadlocks() {
+ var len = requires.length;
+ var dep;
+ while (len--) {
+ if (!(dep = tasks[requires[len]])) {
+ throw new Error('Has non-existent dependency in ' +
+ requires.join(', '));
+ }
+ if (isArray(dep) && indexOf(dep, k) >= 0) {
+ throw new Error('Has cyclic dependencies');
+ }
+ }
+ }
+
+ function ready() {
+ return runningTasks < concurrency &&
+ !baseHas(results, k) &&
+ !hasError &&
+ arrayEvery(requires, function (x) {
+ return baseHas(results, x);
+ });
+ }
+
+ function startNext() {
+ runningTasks++;
+ var taskFn = task[task.length - 1];
+ if (requires.length > 0) {
+ taskFn(results, taskCallback);
+ } else {
+ taskFn(taskCallback);
+ }
+ }
+
+ function listener() {
+ if (ready()) {
+ removeListener(listener);
+ startNext();
+ }
+ }
+ });
+}
diff --git a/lib/cargo.js b/lib/cargo.js
new file mode 100644
index 0000000..b90ab0f
--- /dev/null
+++ b/lib/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/lib/compose.js b/lib/compose.js
new file mode 100644
index 0000000..9e92521
--- /dev/null
+++ b/lib/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/lib/concat.js b/lib/concat.js
new file mode 100644
index 0000000..af019a3
--- /dev/null
+++ b/lib/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/lib/concatSeries.js b/lib/concatSeries.js
new file mode 100644
index 0000000..76f4043
--- /dev/null
+++ b/lib/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/lib/constant.js b/lib/constant.js
new file mode 100644
index 0000000..706507f
--- /dev/null
+++ b/lib/constant.js
@@ -0,0 +1,10 @@
+'use strict';
+
+import rest from 'lodash/rest';
+
+export default rest(function(values) {
+ var args = [null].concat(values);
+ return function (cb) {
+ return cb.apply(this, args);
+ };
+});
diff --git a/lib/detect.js b/lib/detect.js
new file mode 100644
index 0000000..b2c4778
--- /dev/null
+++ b/lib/detect.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import identity from 'lodash/identity';
+
+import createTester from './internal/createTester';
+import eachOf from './eachOf';
+import findGetResult from './internal/findGetResult';
+
+export default createTester(eachOf, identity, findGetResult);
diff --git a/lib/detectLimit.js b/lib/detectLimit.js
new file mode 100644
index 0000000..357786d
--- /dev/null
+++ b/lib/detectLimit.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import identity from 'lodash/identity';
+
+import createTester from './internal/createTester';
+import eachOfLimit from './eachOfLimit';
+import findGetResult from './internal/findGetResult';
+
+export default createTester(eachOfLimit, identity, findGetResult);
diff --git a/lib/detectSeries.js b/lib/detectSeries.js
new file mode 100644
index 0000000..325a500
--- /dev/null
+++ b/lib/detectSeries.js
@@ -0,0 +1,9 @@
+'use strict';
+
+import identity from 'lodash/identity';
+
+import createTester from './internal/createTester';
+import eachOfSeries from './eachOfSeries';
+import findGetResult from './internal/findGetResult';
+
+export default createTester(eachOfSeries, identity, findGetResult);
diff --git a/lib/dir.js b/lib/dir.js
new file mode 100644
index 0000000..049b416
--- /dev/null
+++ b/lib/dir.js
@@ -0,0 +1,5 @@
+'use strict';
+
+import consoleFunc from './internal/consoleFunc';
+
+export default consoleFunc('dir');
diff --git a/lib/doDuring.js b/lib/doDuring.js
new file mode 100644
index 0000000..c13e62b
--- /dev/null
+++ b/lib/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/lib/doUntil.js b/lib/doUntil.js
new file mode 100644
index 0000000..3bc783f
--- /dev/null
+++ b/lib/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/lib/doWhilst.js b/lib/doWhilst.js
new file mode 100644
index 0000000..b05d1d8
--- /dev/null
+++ b/lib/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/lib/during.js b/lib/during.js
new file mode 100644
index 0000000..6b7c4d4
--- /dev/null
+++ b/lib/during.js
@@ -0,0 +1,25 @@
+'use strict';
+
+import noop from 'lodash/noop';
+import rest from 'lodash/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/lib/each.js b/lib/each.js
new file mode 100644
index 0000000..d81763a
--- /dev/null
+++ b/lib/each.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import eachLimit from './eachLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(eachLimit, Infinity);
diff --git a/lib/eachLimit.js b/lib/eachLimit.js
new file mode 100644
index 0000000..5009cc3
--- /dev/null
+++ b/lib/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/lib/eachOf.js b/lib/eachOf.js
new file mode 100644
index 0000000..d16e1b3
--- /dev/null
+++ b/lib/eachOf.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import eachOfLimit from './eachOfLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(eachOfLimit, Infinity);
diff --git a/lib/eachOfLimit.js b/lib/eachOfLimit.js
new file mode 100644
index 0000000..e381474
--- /dev/null
+++ b/lib/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/lib/eachOfSeries.js b/lib/eachOfSeries.js
new file mode 100644
index 0000000..47787bb
--- /dev/null
+++ b/lib/eachOfSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import eachOfLimit from './eachOfLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(eachOfLimit, 1);
diff --git a/lib/eachSeries.js b/lib/eachSeries.js
new file mode 100644
index 0000000..39dc81f
--- /dev/null
+++ b/lib/eachSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import eachLimit from './eachLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(eachLimit, 1);
diff --git a/lib/ensureAsync.js b/lib/ensureAsync.js
new file mode 100644
index 0000000..4f4f762
--- /dev/null
+++ b/lib/ensureAsync.js
@@ -0,0 +1,24 @@
+'use strict';
+
+import rest from 'lodash/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/lib/every.js b/lib/every.js
new file mode 100644
index 0000000..b2d2abd
--- /dev/null
+++ b/lib/every.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import everyLimit from './everyLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(everyLimit, Infinity);
diff --git a/lib/everyLimit.js b/lib/everyLimit.js
new file mode 100644
index 0000000..4b3fc5f
--- /dev/null
+++ b/lib/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/lib/filter.js b/lib/filter.js
new file mode 100644
index 0000000..f3813d4
--- /dev/null
+++ b/lib/filter.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import filterLimit from './filterLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(filterLimit, Infinity);
diff --git a/lib/filterLimit.js b/lib/filterLimit.js
new file mode 100644
index 0000000..8fe237f
--- /dev/null
+++ b/lib/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/lib/filterSeries.js b/lib/filterSeries.js
new file mode 100644
index 0000000..d3995c9
--- /dev/null
+++ b/lib/filterSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import filterLimit from './filterLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(filterLimit, 1);
diff --git a/lib/forever.js b/lib/forever.js
new file mode 100644
index 0000000..82d004a
--- /dev/null
+++ b/lib/forever.js
@@ -0,0 +1,17 @@
+'use strict';
+
+import noop from 'lodash/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/lib/index.js b/lib/index.js
new file mode 100644
index 0000000..2e27f25
--- /dev/null
+++ b/lib/index.js
@@ -0,0 +1,231 @@
+'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 race from './race';
+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,
+ race: race,
+ 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,
+ race as race,
+ 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/lib/internal/applyEach.js b/lib/internal/applyEach.js
new file mode 100644
index 0000000..25bcce1
--- /dev/null
+++ b/lib/internal/applyEach.js
@@ -0,0 +1,22 @@
+'use strict';
+
+import rest from 'lodash/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/lib/internal/concat.js b/lib/internal/concat.js
new file mode 100644
index 0000000..482ad3a
--- /dev/null
+++ b/lib/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/lib/internal/consoleFunc.js b/lib/internal/consoleFunc.js
new file mode 100644
index 0000000..fd8130d
--- /dev/null
+++ b/lib/internal/consoleFunc.js
@@ -0,0 +1,23 @@
+'use strict';
+
+import arrayEach from 'lodash/_arrayEach';
+import rest from 'lodash/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/lib/internal/createTester.js b/lib/internal/createTester.js
new file mode 100644
index 0000000..282ef87
--- /dev/null
+++ b/lib/internal/createTester.js
@@ -0,0 +1,37 @@
+'use strict';
+
+export default function _createTester(eachfn, check, getResult) {
+ return function(arr, limit, iterator, cb) {
+ function done(err) {
+ if (cb) {
+ if (err) {
+ cb(err);
+ } else {
+ cb(null, getResult(false));
+ }
+ }
+ }
+ function iteratee(x, _, callback) {
+ if (!cb) return callback();
+ iterator(x, function (err, v) {
+ if (cb) {
+ if (err) {
+ cb(err);
+ cb = iterator = false;
+ } else if (check(v)) {
+ cb(null, 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/lib/internal/doLimit.js b/lib/internal/doLimit.js
new file mode 100644
index 0000000..16bfa42
--- /dev/null
+++ b/lib/internal/doLimit.js
@@ -0,0 +1,7 @@
+'use strict';
+
+export default function doLimit(fn, limit) {
+ return function (iterable, iterator, callback) {
+ return fn(iterable, limit, iterator, callback);
+ };
+}
diff --git a/lib/internal/doParallel.js b/lib/internal/doParallel.js
new file mode 100644
index 0000000..19c90fc
--- /dev/null
+++ b/lib/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/lib/internal/doParallelLimit.js b/lib/internal/doParallelLimit.js
new file mode 100644
index 0000000..0c3bcf7
--- /dev/null
+++ b/lib/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/lib/internal/doSeries.js b/lib/internal/doSeries.js
new file mode 100644
index 0000000..c7f1d99
--- /dev/null
+++ b/lib/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/lib/internal/eachOfLimit.js b/lib/internal/eachOfLimit.js
new file mode 100644
index 0000000..be1eab8
--- /dev/null
+++ b/lib/internal/eachOfLimit.js
@@ -0,0 +1,49 @@
+'use strict';
+
+import noop from 'lodash/noop';
+import once from 'lodash/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/lib/internal/filter.js b/lib/internal/filter.js
new file mode 100644
index 0000000..8b1de9f
--- /dev/null
+++ b/lib/internal/filter.js
@@ -0,0 +1,30 @@
+'use strict';
+
+import arrayMap from 'lodash/_arrayMap';
+import property from 'lodash/_baseProperty';
+
+export default function _filter(eachfn, arr, iterator, callback) {
+ var results = [];
+ eachfn(arr, function (x, index, callback) {
+ iterator(x, function (err, v) {
+ if (err) {
+ callback(err);
+ }
+ else {
+ if (v) {
+ results.push({index: index, value: x});
+ }
+ callback();
+ }
+ });
+ }, function (err) {
+ if (err) {
+ callback(err);
+ }
+ else {
+ callback(null, arrayMap(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), property('value')));
+ }
+ });
+}
diff --git a/lib/internal/findGetResult.js b/lib/internal/findGetResult.js
new file mode 100644
index 0000000..3aeb07d
--- /dev/null
+++ b/lib/internal/findGetResult.js
@@ -0,0 +1,5 @@
+'use strict';
+
+export default function _findGetResult(v, x) {
+ return x;
+}
diff --git a/lib/internal/keyIterator.js b/lib/internal/keyIterator.js
new file mode 100644
index 0000000..0e2b0c3
--- /dev/null
+++ b/lib/internal/keyIterator.js
@@ -0,0 +1,23 @@
+'use strict';
+
+import isArrayLike from 'lodash/isArrayLike';
+import keys from 'lodash/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/lib/internal/map.js b/lib/internal/map.js
new file mode 100644
index 0000000..a7c19ac
--- /dev/null
+++ b/lib/internal/map.js
@@ -0,0 +1,19 @@
+'use strict';
+
+import isArrayLike from 'lodash/isArrayLike';
+import noop from 'lodash/noop';
+import once from 'lodash/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/lib/internal/notId.js b/lib/internal/notId.js
new file mode 100644
index 0000000..d936aab
--- /dev/null
+++ b/lib/internal/notId.js
@@ -0,0 +1,5 @@
+'use strict';
+
+export default function notId(v) {
+ return !v;
+}
diff --git a/lib/internal/onlyOnce.js b/lib/internal/onlyOnce.js
new file mode 100644
index 0000000..f4241c8
--- /dev/null
+++ b/lib/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/lib/internal/parallel.js b/lib/internal/parallel.js
new file mode 100644
index 0000000..52b0303
--- /dev/null
+++ b/lib/internal/parallel.js
@@ -0,0 +1,22 @@
+'use strict';
+
+import noop from 'lodash/noop';
+import isArrayLike from 'lodash/isArrayLike';
+import rest from 'lodash/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/lib/internal/queue.js b/lib/internal/queue.js
new file mode 100644
index 0000000..3e7eb1e
--- /dev/null
+++ b/lib/internal/queue.js
@@ -0,0 +1,145 @@
+'use strict';
+
+import arrayEach from 'lodash/_arrayEach';
+import arrayMap from 'lodash/_arrayMap';
+import isArray from 'lodash/isArray';
+import noop from 'lodash/noop';
+import property from 'lodash/_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();
+ }
+ if (q.tasks.length <= (q.concurrency - q.buffer) ) {
+ q.unsaturated();
+ }
+ });
+ 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,
+ unsaturated:noop,
+ buffer: concurrency / 4,
+ 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/lib/internal/reject.js b/lib/internal/reject.js
new file mode 100644
index 0000000..708e810
--- /dev/null
+++ b/lib/internal/reject.js
@@ -0,0 +1,15 @@
+'use strict';
+
+import filter from './filter';
+
+export default function reject(eachfn, arr, iterator, callback) {
+ filter(eachfn, arr, function(value, cb) {
+ iterator(value, function(err, v) {
+ if (err) {
+ cb(err);
+ } else {
+ cb(null, !v);
+ }
+ });
+ }, callback);
+}
diff --git a/lib/internal/setImmediate.js b/lib/internal/setImmediate.js
new file mode 100644
index 0000000..c02ad71
--- /dev/null
+++ b/lib/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/lib/internal/withoutIndex.js b/lib/internal/withoutIndex.js
new file mode 100644
index 0000000..f163ff3
--- /dev/null
+++ b/lib/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/lib/iterator.js b/lib/iterator.js
new file mode 100644
index 0000000..568171a
--- /dev/null
+++ b/lib/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/lib/log.js b/lib/log.js
new file mode 100644
index 0000000..b581264
--- /dev/null
+++ b/lib/log.js
@@ -0,0 +1,5 @@
+'use strict';
+
+import consoleFunc from './internal/consoleFunc';
+
+export default consoleFunc('log');
diff --git a/lib/map.js b/lib/map.js
new file mode 100644
index 0000000..cb3f56d
--- /dev/null
+++ b/lib/map.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import mapLimit from './mapLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(mapLimit, Infinity);
diff --git a/lib/mapLimit.js b/lib/mapLimit.js
new file mode 100644
index 0000000..642b4c6
--- /dev/null
+++ b/lib/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/lib/mapSeries.js b/lib/mapSeries.js
new file mode 100644
index 0000000..9a6bd11
--- /dev/null
+++ b/lib/mapSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import mapLimit from './mapLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(mapLimit, 1);
diff --git a/lib/memoize.js b/lib/memoize.js
new file mode 100644
index 0000000..30b989c
--- /dev/null
+++ b/lib/memoize.js
@@ -0,0 +1,37 @@
+'use strict';
+
+import identity from 'lodash/identity';
+import rest from 'lodash/rest';
+import has from 'lodash/has';
+
+import setImmediate from './internal/setImmediate';
+
+export default function memoize(fn, hasher) {
+ var memo = Object.create(null);
+ var queues = Object.create(null);
+ hasher = hasher || identity;
+ var memoized = rest(function memoized(args) {
+ var callback = args.pop();
+ var key = hasher.apply(null, args);
+ if (has(memo, key)) {
+ setImmediate(function() {
+ callback.apply(null, memo[key]);
+ });
+ } else if (has(queues, key)) {
+ 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/lib/nextTick.js b/lib/nextTick.js
new file mode 100644
index 0000000..b61a8b4
--- /dev/null
+++ b/lib/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/lib/parallel.js b/lib/parallel.js
new file mode 100644
index 0000000..6114d6a
--- /dev/null
+++ b/lib/parallel.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import parallelLimit from './parallelLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(parallelLimit, Infinity);
diff --git a/lib/parallelLimit.js b/lib/parallelLimit.js
new file mode 100644
index 0000000..7e66bed
--- /dev/null
+++ b/lib/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/lib/priorityQueue.js b/lib/priorityQueue.js
new file mode 100644
index 0000000..90ca03e
--- /dev/null
+++ b/lib/priorityQueue.js
@@ -0,0 +1,75 @@
+'use strict';
+
+import arrayEach from 'lodash/_arrayEach';
+import isArray from 'lodash/isArray';
+import noop from 'lodash/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();
+ }
+ if (q.tasks.length <= (q.concurrency - q.buffer) ) {
+ q.unsaturated();
+ }
+ 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/lib/queue.js b/lib/queue.js
new file mode 100644
index 0000000..de2ac93
--- /dev/null
+++ b/lib/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/lib/race.js b/lib/race.js
new file mode 100644
index 0000000..4a5f8a5
--- /dev/null
+++ b/lib/race.js
@@ -0,0 +1,14 @@
+'use strict';
+
+import isArray from 'lodash/isArray';
+import noop from 'lodash/noop';
+import once from 'lodash/once';
+
+export default function race(tasks, cb) {
+ cb = once(cb || noop);
+ if (!isArray(tasks)) return cb(new TypeError('First argument to race must be an array of functions'));
+ if (!tasks.length) return cb();
+ for (let i = 0; i < tasks.length; i++) {
+ tasks[i](cb);
+ }
+}
diff --git a/lib/reduce.js b/lib/reduce.js
new file mode 100644
index 0000000..51b736a
--- /dev/null
+++ b/lib/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/lib/reduceRight.js b/lib/reduceRight.js
new file mode 100644
index 0000000..730e320
--- /dev/null
+++ b/lib/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/lib/reject.js b/lib/reject.js
new file mode 100644
index 0000000..970a0ec
--- /dev/null
+++ b/lib/reject.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import rejectLimit from './rejectLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(rejectLimit, Infinity);
diff --git a/lib/rejectLimit.js b/lib/rejectLimit.js
new file mode 100644
index 0000000..7cefed6
--- /dev/null
+++ b/lib/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/lib/rejectSeries.js b/lib/rejectSeries.js
new file mode 100644
index 0000000..00c145f
--- /dev/null
+++ b/lib/rejectSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import rejectLimit from './rejectLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(rejectLimit, 1);
diff --git a/lib/retry.js b/lib/retry.js
new file mode 100644
index 0000000..506a424
--- /dev/null
+++ b/lib/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/lib/seq.js b/lib/seq.js
new file mode 100644
index 0000000..966e751
--- /dev/null
+++ b/lib/seq.js
@@ -0,0 +1,28 @@
+'use strict';
+
+import noop from 'lodash/noop';
+import rest from 'lodash/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/lib/series.js b/lib/series.js
new file mode 100644
index 0000000..bd8e15d
--- /dev/null
+++ b/lib/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/lib/setImmediate.js b/lib/setImmediate.js
new file mode 100644
index 0000000..05d9555
--- /dev/null
+++ b/lib/setImmediate.js
@@ -0,0 +1,5 @@
+'use strict';
+
+import setImmediate from './internal/setImmediate';
+
+export default setImmediate;
diff --git a/lib/some.js b/lib/some.js
new file mode 100644
index 0000000..000f2e2
--- /dev/null
+++ b/lib/some.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import someLimit from './someLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(someLimit, Infinity);
diff --git a/lib/someLimit.js b/lib/someLimit.js
new file mode 100644
index 0000000..498a262
--- /dev/null
+++ b/lib/someLimit.js
@@ -0,0 +1,7 @@
+'use strict';
+
+import createTester from './internal/createTester';
+import eachOfLimit from './eachOfLimit';
+import identity from 'lodash/identity';
+
+export default createTester(eachOfLimit, Boolean, identity);
diff --git a/lib/sortBy.js b/lib/sortBy.js
new file mode 100644
index 0000000..4f14823
--- /dev/null
+++ b/lib/sortBy.js
@@ -0,0 +1,23 @@
+'use strict';
+
+import arrayMap from 'lodash/_arrayMap';
+import property from 'lodash/_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/lib/times.js b/lib/times.js
new file mode 100644
index 0000000..2cbd230
--- /dev/null
+++ b/lib/times.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import timesLimit from './timesLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(timesLimit, Infinity);
diff --git a/lib/timesLimit.js b/lib/timesLimit.js
new file mode 100644
index 0000000..1ea7313
--- /dev/null
+++ b/lib/timesLimit.js
@@ -0,0 +1,8 @@
+'use strict';
+
+import mapLimit from './mapLimit';
+import range from 'lodash/_baseRange';
+
+export default function timeLimit(count, limit, iterator, cb) {
+ return mapLimit(range(0, count, 1), limit, iterator, cb);
+}
diff --git a/lib/timesSeries.js b/lib/timesSeries.js
new file mode 100644
index 0000000..af2219b
--- /dev/null
+++ b/lib/timesSeries.js
@@ -0,0 +1,6 @@
+'use strict';
+
+import timesLimit from './timesLimit';
+import doLimit from './internal/doLimit';
+
+export default doLimit(timesLimit, 1);
diff --git a/lib/transform.js b/lib/transform.js
new file mode 100644
index 0000000..3dddae8
--- /dev/null
+++ b/lib/transform.js
@@ -0,0 +1,19 @@
+'use strict';
+
+import isArray from 'lodash/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/lib/unmemoize.js b/lib/unmemoize.js
new file mode 100644
index 0000000..d652e7b
--- /dev/null
+++ b/lib/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/lib/until.js b/lib/until.js
new file mode 100644
index 0000000..f9ed2fd
--- /dev/null
+++ b/lib/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/lib/waterfall.js b/lib/waterfall.js
new file mode 100644
index 0000000..8867c87
--- /dev/null
+++ b/lib/waterfall.js
@@ -0,0 +1,32 @@
+'use strict';
+
+import isArray from 'lodash/isArray';
+import noop from 'lodash/noop';
+import once from 'lodash/once';
+import rest from 'lodash/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/lib/whilst.js b/lib/whilst.js
new file mode 100644
index 0000000..feaec00
--- /dev/null
+++ b/lib/whilst.js
@@ -0,0 +1,15 @@
+'use strict';
+
+import noop from 'lodash/noop';
+import rest from 'lodash/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/mocha_test/auto.js b/mocha_test/auto.js
new file mode 100644
index 0000000..c6b7150
--- /dev/null
+++ b/mocha_test/auto.js
@@ -0,0 +1,347 @@
+var async = require('../lib');
+var expect = require('chai').expect;
+var _ = require('lodash');
+
+describe('auto', function () {
+
+ it('auto', function(done){
+ var callOrder = [];
+ async.auto({
+ task1: ['task2', function(results, callback){
+ setTimeout(function(){
+ callOrder.push('task1');
+ callback();
+ }, 25);
+ }],
+ task2: function(callback){
+ setTimeout(function(){
+ callOrder.push('task2');
+ callback();
+ }, 50);
+ },
+ task3: ['task2', function(results, callback){
+ callOrder.push('task3');
+ callback();
+ }],
+ task4: ['task1', 'task2', function(results, callback){
+ callOrder.push('task4');
+ callback();
+ }],
+ task5: ['task2', function(results, callback){
+ setTimeout(function(){
+ callOrder.push('task5');
+ callback();
+ }, 0);
+ }],
+ task6: ['task2', function(results, callback){
+ callOrder.push('task6');
+ callback();
+ }]
+ },
+ function(err){
+ expect(err).to.equal(null);
+ expect(callOrder).to.eql(['task2','task6','task3','task5','task1','task4']);
+ done();
+ });
+ });
+
+ it('auto concurrency', function (done) {
+ var concurrency = 2;
+ var runningTasks = [];
+
+ function makeCallback(taskName) {
+ return function(/*..., callback*/) {
+ var callback = _.last(arguments);
+ runningTasks.push(taskName);
+ setTimeout(function(){
+ // Each task returns the array of running tasks as results.
+ var result = runningTasks.slice(0);
+ runningTasks.splice(runningTasks.indexOf(taskName), 1);
+ callback(null, result);
+ });
+ };
+ }
+
+ async.auto({
+ task1: ['task2', makeCallback('task1')],
+ task2: makeCallback('task2'),
+ task3: ['task2', makeCallback('task3')],
+ task4: ['task1', 'task2', makeCallback('task4')],
+ task5: ['task2', makeCallback('task5')],
+ task6: ['task2', makeCallback('task6')]
+ }, concurrency, function(err, results){
+ _.each(results, function(result) {
+ expect(result.length).to.be.below(concurrency + 1);
+ });
+ done();
+ });
+ });
+
+ it('auto petrify', function (done) {
+ var callOrder = [];
+ async.auto({
+ task1: ['task2', function (results, callback) {
+ setTimeout(function () {
+ callOrder.push('task1');
+ callback();
+ }, 100);
+ }],
+ task2: function (callback) {
+ setTimeout(function () {
+ callOrder.push('task2');
+ callback();
+ }, 200);
+ },
+ task3: ['task2', function (results, callback) {
+ callOrder.push('task3');
+ callback();
+ }],
+ task4: ['task1', 'task2', function (results, callback) {
+ callOrder.push('task4');
+ callback();
+ }]
+ },
+ function (err) {
+ if (err) throw err;
+ expect(callOrder).to.eql(['task2', 'task3', 'task1', 'task4']);
+ done();
+ });
+ });
+
+ it('auto results', function(done){
+ var callOrder = [];
+ async.auto({
+ task1: ['task2', function(results, callback){
+ expect(results.task2).to.eql('task2');
+ setTimeout(function(){
+ callOrder.push('task1');
+ callback(null, 'task1a', 'task1b');
+ }, 25);
+ }],
+ task2: function(callback){
+ setTimeout(function(){
+ callOrder.push('task2');
+ callback(null, 'task2');
+ }, 50);
+ },
+ task3: ['task2', function(results, callback){
+ expect(results.task2).to.eql('task2');
+ callOrder.push('task3');
+ callback(null);
+ }],
+ task4: ['task1', 'task2', function(results, callback){
+ expect(results.task1).to.eql(['task1a','task1b']);
+ expect(results.task2).to.eql('task2');
+ callOrder.push('task4');
+ callback(null, 'task4');
+ }]
+ },
+ function(err, results){
+ expect(callOrder).to.eql(['task2','task3','task1','task4']);
+ expect(results).to.eql({task1: ['task1a','task1b'], task2: 'task2', task3: undefined, task4: 'task4'});
+ done();
+ });
+ });
+
+ it('auto empty object', function(done){
+ async.auto({}, function(err){
+ expect(err).to.equal(null);
+ done();
+ });
+ });
+
+ it('auto error', function(done){
+ async.auto({
+ task1: function(callback){
+ callback('testerror');
+ },
+ task2: ['task1', function(results, callback){
+ throw new Error('task2 should not be called');
+ }],
+ task3: function(callback){
+ callback('testerror2');
+ }
+ },
+ function(err){
+ expect(err).to.equal('testerror');
+ });
+ setTimeout(done, 100);
+ });
+
+ it('auto no callback', function(done){
+ async.auto({
+ task1: function(callback){callback();},
+ task2: ['task1', function(results, callback){callback(); done();}]
+ });
+ });
+
+ it('auto concurrency no callback', function(done){
+ async.auto({
+ task1: function(callback){callback();},
+ task2: ['task1', function(results, callback){callback(); done();}]
+ }, 1);
+ });
+
+ it('auto error should pass partial results', function(done) {
+ async.auto({
+ task1: function(callback){
+ callback(false, 'result1');
+ },
+ task2: ['task1', function(results, callback){
+ callback('testerror', 'result2');
+ }],
+ task3: ['task2', function(){
+ throw new Error('task3 should not be called');
+ }]
+ },
+ function(err, results){
+ expect(err).to.equal('testerror');
+ expect(results.task1).to.equal('result1');
+ expect(results.task2).to.equal('result2');
+ done();
+ });
+ });
+
+ // Issue 24 on github: https://github.com/caolan/async/issues#issue/24
+ // Issue 76 on github: https://github.com/caolan/async/issues#issue/76
+ it('auto removeListener has side effect on loop iterator', function(done) {
+ async.auto({
+ task1: ['task3', function(/*callback*/) { done(); }],
+ task2: ['task3', function(/*callback*/) { /* by design: DON'T call callback */ }],
+ task3: function(callback) { callback(); }
+ });
+ });
+
+ // Issue 410 on github: https://github.com/caolan/async/issues/410
+ it('auto calls callback multiple times', function(done) {
+ if (process.browser) {
+ // node only test
+ return done();
+ }
+ var finalCallCount = 0;
+ var domain = require('domain').create();
+ domain.on('error', function (e) {
+ // ignore test error
+ if (!e._test_error) {
+ return done(e);
+ }
+ });
+ domain.run(function () {
+ async.auto({
+ task1: function(callback) { callback(null); },
+ task2: ['task1', function(results, callback) { callback(null); }]
+ },
+
+ // Error throwing final callback. This should only run once
+ function() {
+ finalCallCount++;
+ var e = new Error('An error');
+ e._test_error = true;
+ throw e;
+ });
+ });
+ setTimeout(function () {
+ expect(finalCallCount).to.equal(1);
+ done();
+ }, 10);
+ });
+
+
+ it('auto calls callback multiple times with parallel functions', function(done) {
+ async.auto({
+ task1: function(callback) { setTimeout(callback,0,'err'); },
+ task2: function(callback) { setTimeout(callback,0,'err'); }
+ },
+ // Error throwing final callback. This should only run once
+ function(err) {
+ expect(err).to.equal('err');
+ done();
+ });
+ });
+
+
+ // Issue 462 on github: https://github.com/caolan/async/issues/462
+ it('auto modifying results causes final callback to run early', function(done) {
+ async.auto({
+ task1: function(callback){
+ callback(null, 'task1');
+ },
+ task2: ['task1', function(results, callback){
+ results.inserted = true;
+ setTimeout(function(){
+ callback(null, 'task2');
+ }, 50);
+ }],
+ task3: function(callback){
+ setTimeout(function(){
+ callback(null, 'task3');
+ }, 100);
+ }
+ },
+ function(err, results){
+ expect(results.inserted).to.equal(true);
+ expect(results.task3).to.equal('task3');
+ done();
+ });
+ });
+
+ // Issue 263 on github: https://github.com/caolan/async/issues/263
+ it('auto prevent dead-locks due to inexistant dependencies', function(done) {
+ expect(function () {
+ async.auto({
+ task1: ['noexist', function(results, callback){
+ callback(null, 'task1');
+ }]
+ });
+ }).to.throw;
+ done();
+ });
+
+ // Issue 263 on github: https://github.com/caolan/async/issues/263
+ it('auto prevent dead-locks due to cyclic dependencies', function(done) {
+ expect(function () {
+ async.auto({
+ task1: ['task2', function(results, callback){
+ callback(null, 'task1');
+ }],
+ task2: ['task1', function(results, callback){
+ callback(null, 'task2');
+ }]
+ });
+ }).to.throw;
+ done();
+ });
+
+ // Issue 988 on github: https://github.com/caolan/async/issues/988
+ it('auto stops running tasks on error', function(done) {
+ async.auto({
+ task1: function (callback) {
+ callback('error');
+ },
+ task2: function (callback) {
+ throw new Error('test2 should not be called');
+ }
+ }, 1, function (error) {
+ expect(error).to.equal('error');
+ done();
+ });
+ });
+
+ it('ignores results after an error', function (done) {
+ async.auto({
+ task1: function (cb) {
+ setTimeout(cb, 25, 'error');
+ },
+ task2: function (cb) {
+ setTimeout(cb, 30, null);
+ },
+ task3: ['task2', function () {
+ throw new Error("task should not have been called");
+ }]
+ }, function (err) {
+ expect(err).to.equal('error');
+ setTimeout(done, 25, null);
+ });
+ });
+
+});
diff --git a/mocha_test/compose.js b/mocha_test/compose.js
index 85306a5..5be9192 100644
--- a/mocha_test/compose.js
+++ b/mocha_test/compose.js
@@ -1,4 +1,4 @@
-var async = require('../lib/async');
+var async = require('../lib');
var expect = require('chai').expect;
describe('compose', function(){
diff --git a/mocha_test/detect.js b/mocha_test/detect.js
new file mode 100644
index 0000000..e1eec79
--- /dev/null
+++ b/mocha_test/detect.js
@@ -0,0 +1,123 @@
+var async = require('../lib');
+var expect = require('chai').expect;
+
+describe("detect", function () {
+
+ function detectIterator(call_order, x, callback) {
+ setTimeout(function(){
+ call_order.push(x);
+ callback(null, x == 2);
+ }, x*25);
+ }
+
+ it('detect', function(done){
+ var call_order = [];
+ async.detect([3,2,1], detectIterator.bind(this, call_order), function(err, result){
+ call_order.push('callback');
+ expect(err).to.equal(null);
+ expect(result).to.equal(2);
+ });
+ setTimeout(function(){
+ expect(call_order).to.eql([1,2,'callback',3]);
+ done();
+ }, 100);
+ });
+
+ it('detect - mulitple matches', function(done){
+ var call_order = [];
+ async.detect([3,2,2,1,2], detectIterator.bind(this, call_order), function(err, result){
+ call_order.push('callback');
+ expect(err).to.equal(null);
+ expect(result).to.equal(2);
+ });
+ setTimeout(function(){
+ expect(call_order).to.eql([1,2,'callback',2,2,3]);
+ done();
+ }, 100);
+ });
+
+ it('detect error', function(done){
+ async.detect([3,2,1], function(x, callback) {
+ setTimeout(function(){callback('error');}, 0);
+ }, function(err, result){
+ expect(err).to.equal('error');
+ expect(result).to.not.exist;
+ done();
+ });
+ });
+
+ it('detectSeries', function(done){
+ var call_order = [];
+ async.detectSeries([3,2,1], detectIterator.bind(this, call_order), function(err, result){
+ call_order.push('callback');
+ expect(err).to.equal(null);
+ expect(result).to.equal(2);
+ });
+ setTimeout(function(){
+ expect(call_order).to.eql([3,2,'callback']);
+ done();
+ }, 200);
+ });
+
+ it('detectSeries - multiple matches', function(done){
+ var call_order = [];
+ async.detectSeries([3,2,2,1,2], detectIterator.bind(this, call_order), function(err, result){
+ call_order.push('callback');
+ expect(err).to.equal(null);
+ expect(result).to.equal(2);
+ });
+ setTimeout(function(){
+ expect(call_order).to.eql([3,2,'callback']);
+ done();
+ }, 200);
+ });
+
+ it('detectSeries - ensure stop', function (done) {
+ async.detectSeries([1, 2, 3, 4, 5], function (num, cb) {
+ if (num > 3) throw new Error("detectSeries did not stop iterating");
+ cb(null, num === 3);
+ }, function (err, result) {
+ expect(err).to.equal(null);
+ expect(result).to.equal(3);
+ done();
+ });
+ });
+
+ it('detectLimit', function(done){
+ var call_order = [];
+ async.detectLimit([3, 2, 1], 2, detectIterator.bind(this, call_order), function(err, result) {
+ call_order.push('callback');
+ expect(err).to.equal(null);
+ expect(result).to.equal(2);
+ });
+ setTimeout(function() {
+ expect(call_order).to.eql([2, 'callback', 3]);
+ done();
+ }, 100);
+ });
+
+ it('detectLimit - multiple matches', function(done){
+ var call_order = [];
+ async.detectLimit([3,2,2,1,2], 2, detectIterator.bind(this, call_order), function(err, result){
+ call_order.push('callback');
+ expect(err).to.equal(null);
+ expect(result).to.equal(2);
+ });
+ setTimeout(function(){
+ expect(call_order).to.eql([2, 'callback', 3]);
+ done();
+ }, 100);
+ });
+
+ it('detectLimit - ensure stop', function (done) {
+ async.detectLimit([1, 2, 3, 4, 5], 2, function (num, cb) {
+ if (num > 4) throw new Error("detectLimit did not stop iterating");
+ cb(null, num === 3);
+ }, function (err, result) {
+ expect(err).to.equal(null);
+ expect(result).to.equal(3);
+ done();
+ });
+ });
+
+});
diff --git a/mocha_test/every.js b/mocha_test/every.js
new file mode 100644
index 0000000..2f562ce
--- /dev/null
+++ b/mocha_test/every.js
@@ -0,0 +1,90 @@
+var async = require('../lib');
+var expect = require('chai').expect;
+
+describe("every", function () {
+
+ it('everyLimit true', function(done){
+ async.everyLimit([3,1,2], 1, function(x, callback){
+ setTimeout(function(){callback(null, x >= 1);}, 0);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(true);
+ done();
+ });
+ });
+
+ it('everyLimit false', function(done){
+ async.everyLimit([3,1,2], 2, function(x, callback){
+ setTimeout(function(){callback(null, x === 2);}, 0);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(false);
+ done();
+ });
+ });
+
+ it('everyLimit short-circuit', function(done){
+ var calls = 0;
+ async.everyLimit([3,1,2], 1, function(x, callback){
+ calls++;
+ callback(null, x === 1);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(false);
+ expect(calls).to.equal(1);
+ done();
+ });
+ });
+
+
+ it('true', function(done){
+ async.every([1,2,3], function(x, callback){
+ setTimeout(function(){callback(null, true);}, 0);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(true);
+ done();
+ });
+ });
+
+ it('false', function(done){
+ async.every([1,2,3], function(x, callback){
+ setTimeout(function(){callback(null, x % 2);}, 0);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(false);
+ done();
+ });
+ });
+
+ it('early return', function(done){
+ var call_order = [];
+ async.every([1,2,3], function(x, callback){
+ setTimeout(function(){
+ call_order.push(x);
+ callback(null, x === 1);
+ }, x*25);
+ }, function(){
+ call_order.push('callback');
+ });
+ setTimeout(function(){
+ expect(call_order).to.eql([1,2,'callback',3]);
+ done();
+ }, 100);
+ });
+
+ it('error', function(done){
+ async.every([1,2,3], function(x, callback){
+ setTimeout(function(){callback('error');}, 0);
+ }, function(err, result){
+ expect(err).to.equal('error');
+ expect(result).to.not.exist;
+ done();
+ });
+ });
+
+ it('all alias', function(){
+ expect(async.all).to.equal(async.every);
+ });
+
+});
diff --git a/mocha_test/filter.js b/mocha_test/filter.js
new file mode 100644
index 0000000..58f9a0b
--- /dev/null
+++ b/mocha_test/filter.js
@@ -0,0 +1,132 @@
+var async = require('../lib');
+var expect = require('chai').expect;
+
+function filterIterator(x, callback) {
+ setTimeout(function(){
+ callback(null, x % 2);
+ }, x*25);
+}
+
+function testLimit(arr, limitFunc, limit, iter, done) {
+ var args = [];
+
+ limitFunc(arr, limit, function(x) {
+ args.push(x);
+ iter.apply(this, arguments);
+ }, function() {
+ expect(args).to.eql(arr);
+ done.apply(this, arguments);
+ });
+}
+
+describe("filter", function () {
+
+ it('filter', function(done){
+ async.filter([3,1,2], filterIterator, function(err, results){
+ expect(err).to.equal(null);
+ expect(results).to.eql([3,1]);
+ done();
+ });
+ });
+
+ it('filter original untouched', function(done){
+ var a = [3,1,2];
+ async.filter(a, function(x, callback){
+ callback(null, x % 2);
+ }, function(err, results){
+ expect(err).to.equal(null);
+ expect(results).to.eql([3,1]);
+ expect(a).to.eql([3,1,2]);
+ done();
+ });
+ });
+
+ it('filter error', function(done){
+ async.filter([3,1,2], function(x, callback){
+ callback('error');
+ } , function(err, results){
+ expect(err).to.equal('error');
+ expect(results).to.not.exist;
+ done();
+ });
+ });
+
+ it('filterSeries', function(done){
+ async.filterSeries([3,1,2], filterIterator, function(err, results){
+ expect(err).to.equal(null);
+ expect(results).to.eql([3,1]);
+ done();
+ });
+ });
+
+ it('select alias', function(){
+ expect(async.select).to.equal(async.filter);
+ });
+
+ it('selectSeries alias', function(){
+ expect(async.selectSeries).to.equal(async.filterSeries);
+ });
+
+ it('filterLimit', function(done) {
+ testLimit([5, 4, 3, 2, 1], async.filterLimit, 2, function(v, next) {
+ next(null, v % 2);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.eql([5, 3, 1]);
+ done();
+ });
+ });
+
+});
+
+describe("reject", function () {
+
+ it('reject', function(done){
+ async.reject([3,1,2], filterIterator, function(err, results){
+ expect(err).to.equal(null);
+ expect(results).to.eql([2]);
+ done();
+ });
+ });
+
+ it('reject original untouched', function(done){
+ var a = [3,1,2];
+ async.reject(a, function(x, callback){
+ callback(null, x % 2);
+ }, function(err, results){
+ expect(err).to.equal(null);
+ expect(results).to.eql([2]);
+ expect(a).to.eql([3,1,2]);
+ done();
+ });
+ });
+
+ it('reject error', function(done){
+ async.reject([3,1,2], function(x, callback){
+ callback('error');
+ } , function(err, results){
+ expect(err).to.equal('error');
+ expect(results).to.not.exist;
+ done();
+ });
+ });
+
+ it('rejectSeries', function(done){
+ async.rejectSeries([3,1,2], filterIterator, function(err, results){
+ expect(err).to.equal(null);
+ expect(results).to.eql([2]);
+ done();
+ });
+ });
+
+ it('rejectLimit', function(done) {
+ testLimit([5, 4, 3, 2, 1], async.rejectLimit, 2, function(v, next) {
+ next(null, v % 2);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.eql([4, 2]);
+ done();
+ });
+ });
+
+});
diff --git a/mocha_test/forever.js b/mocha_test/forever.js
index 970c422..ec21ed7 100644
--- a/mocha_test/forever.js
+++ b/mocha_test/forever.js
@@ -1,4 +1,4 @@
-var async = require('../lib/async');
+var async = require('../lib');
var expect = require('chai').expect;
var isBrowser = require('./support/is_browser');
diff --git a/mocha_test/mocha.opts b/mocha_test/mocha.opts
new file mode 100644
index 0000000..f39ac0a
--- /dev/null
+++ b/mocha_test/mocha.opts
@@ -0,0 +1,4 @@
+--compilers js:babel-core/register
+--recursive
+--growl
+--ui bdd
diff --git a/mocha_test/priorityQueue.js b/mocha_test/priorityQueue.js
new file mode 100644
index 0000000..9832b43
--- /dev/null
+++ b/mocha_test/priorityQueue.js
@@ -0,0 +1,70 @@
+var async = require('../lib');
+var expect = require('chai').expect;
+
+describe('priorityQueue', function() {
+ context('q.unsaturated(): ',function() {
+ it('should have a default buffer property that equals 25% of the concurrenct rate', function(done) {
+ var calls = [];
+ var q = async.priorityQueue(function(task, cb) {
+ // nop
+ calls.push('process ' + task);
+ async.setImmediate(cb);
+ }, 10);
+ expect(q.buffer).to.equal(2.5);
+ done();
+ });
+
+ it('should allow a user to change the buffer property', function(done) {
+ var calls = [];
+ var q = async.priorityQueue(function(task, cb) {
+ // nop
+ calls.push('process ' + task);
+ async.setImmediate(cb);
+ }, 10);
+ q.buffer = 4;
+ expect(q.buffer).to.not.equal(2.5);
+ expect(q.buffer).to.equal(4);
+ done();
+ });
+
+ it('should call the unsaturated callback if tasks length is less than concurrency minus buffer', function(done) {
+ var calls = [];
+ var q = async.priorityQueue(function(task, cb) {
+ calls.push('process ' + task);
+ async.setImmediate(cb);
+ }, 10);
+ q.unsaturated = function() {
+ calls.push('unsaturated');
+ };
+ q.empty = function() {
+ expect(calls.indexOf('unsaturated')).to.be.above(-1);
+ setTimeout(function() {
+ expect(calls).eql([
+ 'unsaturated',
+ 'unsaturated',
+ 'unsaturated',
+ 'unsaturated',
+ 'unsaturated',
+ 'process foo4',
+ 'process foo3',
+ 'process foo2',
+ 'process foo1',
+ 'process foo0',
+ 'foo4 cb',
+ 'foo3 cb',
+ 'foo2 cb',
+ 'foo1 cb',
+ 'foo0 cb'
+ ]);
+ done();
+ }, 50);
+ };
+ q.push('foo0', 5, function () {calls.push('foo0 cb');});
+ q.push('foo1', 4, function () {calls.push('foo1 cb');});
+ q.push('foo2', 3, function () {calls.push('foo2 cb');});
+ q.push('foo3', 2, function () {calls.push('foo3 cb');});
+ q.push('foo4', 1, function () {calls.push('foo4 cb');});
+ });
+ });
+});
+
diff --git a/mocha_test/queue.js b/mocha_test/queue.js
new file mode 100644
index 0000000..f64eef5
--- /dev/null
+++ b/mocha_test/queue.js
@@ -0,0 +1,69 @@
+var async = require('../lib');
+var expect = require('chai').expect;
+
+
+describe('queue', function(){
+ context('q.unsaturated(): ',function() {
+ it('should have a default buffer property that equals 25% of the concurrenct rate', function(done){
+ var calls = [];
+ var q = async.queue(function(task, cb) {
+ // nop
+ calls.push('process ' + task);
+ async.setImmediate(cb);
+ }, 10);
+ expect(q.buffer).to.equal(2.5);
+ done();
+ });
+ it('should allow a user to change the buffer property', function(done){
+ var calls = [];
+ var q = async.queue(function(task, cb) {
+ // nop
+ calls.push('process ' + task);
+ async.setImmediate(cb);
+ }, 10);
+ q.buffer = 4;
+ expect(q.buffer).to.not.equal(2.5);
+ expect(q.buffer).to.equal(4);
+ done();
+ });
+ it('should call the unsaturated callback if tasks length is less than concurrency minus buffer', function(done){
+ var calls = [];
+ var q = async.queue(function(task, cb) {
+ calls.push('process ' + task);
+ async.setImmediate(cb);
+ }, 10);
+ q.unsaturated = function() {
+ calls.push('unsaturated');
+ };
+ q.empty = function() {
+ expect(calls.indexOf('unsaturated')).to.be.above(-1);
+ setTimeout(function() {
+ expect(calls).eql([
+ 'unsaturated',
+ 'unsaturated',
+ 'unsaturated',
+ 'unsaturated',
+ 'unsaturated',
+ 'process foo0',
+ 'process foo1',
+ 'process foo2',
+ 'process foo3',
+ 'process foo4',
+ 'foo0 cb',
+ 'foo1 cb',
+ 'foo2 cb',
+ 'foo3 cb',
+ 'foo4 cb'
+ ]);
+ done();
+ }, 50);
+ };
+ q.push('foo0', function () {calls.push('foo0 cb');});
+ q.push('foo1', function () {calls.push('foo1 cb');});
+ q.push('foo2', function () {calls.push('foo2 cb');});
+ q.push('foo3', function () {calls.push('foo3 cb');});
+ q.push('foo4', function () {calls.push('foo4 cb');});
+ });
+ });
+});
+
diff --git a/mocha_test/race.js b/mocha_test/race.js
new file mode 100644
index 0000000..d56205d
--- /dev/null
+++ b/mocha_test/race.js
@@ -0,0 +1,70 @@
+var async = require('../lib');
+var assert = require('assert');
+
+describe('race', function () {
+ it('should call each function in parallel and callback with first result', function raceTest10(done) {
+ var finished = 0;
+ var tasks = [];
+ function eachTest(i) {
+ var index = i;
+ return function (next) {
+ finished++;
+ next(null, index);
+ };
+ }
+ for (var i = 0; i < 10; i++) {
+ tasks[i] = eachTest(i);
+ }
+ async.race(tasks, function (err, result) {
+ assert.ifError(err);
+ //0 finished first
+ assert.strictEqual(result, 0);
+ assert.strictEqual(finished, 1);
+ async.setImmediate(function () {
+ assert.strictEqual(finished, 10);
+ done();
+ });
+ });
+ });
+ it('should callback with the first error', function raceTest20(done) {
+ var tasks = [];
+ function eachTest(i) {
+ var index = i;
+ return function (next) {
+ setTimeout(function () {
+ next(new Error('ERR' + index));
+ }, 50 - index * 2);
+ };
+ }
+ for (var i = 0; i <= 5; i++) {
+ tasks[i] = eachTest(i);
+ }
+ async.race(tasks, function (err, result) {
+ assert.ok(err);
+ assert.ok(err instanceof Error);
+ assert.strictEqual(typeof result, 'undefined');
+ assert.strictEqual(err.message, 'ERR5');
+ done();
+ });
+ });
+ it('should callback when task is empty', function raceTest30(done) {
+ async.race([], function (err, result) {
+ assert.ifError(err);
+ assert.strictEqual(typeof result, 'undefined');
+ done();
+ });
+ });
+ it('should callback in error the task arg is not an Array', function raceTest40() {
+ var errors = [];
+ async.race(null, function (err) {
+ errors.push(err);
+ });
+ async.race({}, function (err) {
+ errors.push(err);
+ });
+ assert.strictEqual(errors.length, 2);
+ assert.ok(errors[0] instanceof TypeError);
+ assert.ok(errors[1] instanceof TypeError);
+ });
+});
+
diff --git a/mocha_test/some.js b/mocha_test/some.js
new file mode 100644
index 0000000..8bdcb6b
--- /dev/null
+++ b/mocha_test/some.js
@@ -0,0 +1,91 @@
+var async = require('../lib');
+var expect = require('chai').expect;
+
+describe("some", function () {
+
+ it('some true', function(done){
+ async.some([3,1,2], function(x, callback){
+ setTimeout(function(){callback(null, x === 1);}, 0);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(true);
+ done();
+ });
+ });
+
+ it('some false', function(done){
+ async.some([3,1,2], function(x, callback){
+ setTimeout(function(){callback(null, x === 10);}, 0);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(false);
+ done();
+ });
+ });
+
+ it('some early return', function(done){
+ var call_order = [];
+ async.some([1,2,3], function(x, callback){
+ setTimeout(function(){
+ call_order.push(x);
+ callback(null, x === 1);
+ }, x*25);
+ }, function(){
+ call_order.push('callback');
+ });
+ setTimeout(function(){
+ expect(call_order).to.eql([1,'callback',2,3]);
+ done();
+ }, 100);
+ });
+
+ it('some error', function(done){
+ async.some([3,1,2], function(x, callback){
+ setTimeout(function(){callback('error');}, 0);
+ }, function(err, result){
+ expect(err).to.equal('error');
+ expect(result).to.not.exist;
+ done();
+ });
+ });
+
+ it('someLimit true', function(done){
+ async.someLimit([3,1,2], 2, function(x, callback){
+ setTimeout(function(){callback(null, x === 2);}, 0);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(true);
+ done();
+ });
+ });
+
+ it('someLimit false', function(done){
+ async.someLimit([3,1,2], 2, function(x, callback){
+ setTimeout(function(){callback(null, x === 10);}, 0);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(false);
+ done();
+ });
+ });
+
+
+ it('someLimit short-circuit', function(done){
+ var calls = 0;
+ async.someLimit([3,1,2], 1, function(x, callback){
+ calls++;
+ callback(null, x === 1);
+ }, function(err, result){
+ expect(err).to.equal(null);
+ expect(result).to.equal(true);
+ expect(calls).to.equal(2);
+ done();
+ });
+ });
+
+ it('any alias', function(){
+ expect(async.any).to.equal(async.some);
+ });
+
+
+});
diff --git a/package.json b/package.json
index 2d366b8..76f9fac 100644
--- a/package.json
+++ b/package.json
@@ -1,20 +1,9 @@
{
"name": "async",
"description": "Higher-order functions and common patterns for asynchronous code",
- "main": "lib/async.js",
- "files": [
- "lib",
- "dist/async.js",
- "dist/async.min.js"
- ],
+ "version": "2.0.0-alpha",
+ "main": "dist/async.js",
"author": "Caolan McMahon",
- "version": "1.5.1",
- "keywords": [
- "async",
- "callback",
- "utility",
- "module"
- ],
"repository": {
"type": "git",
"url": "https://github.com/caolan/async.git"
@@ -22,13 +11,30 @@
"bugs": {
"url": "https://github.com/caolan/async/issues"
},
- "license": "MIT",
+ "keywords": [
+ "async",
+ "callback",
+ "module",
+ "utility"
+ ],
+ "dependencies": {
+ "lodash": "^4.3.0",
+ "lodash-es": "^4.3.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",
@@ -36,22 +42,36 @@
"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",
- "xyz": "^0.5.0",
+ "vinyl-buffer": "~1.0.0",
+ "vinyl-source-stream": "~1.1.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": "lib/async.js",
+ "main": "dist/async.js",
"include": [
- "lib/async.js",
+ "dist/async.js",
"README.md",
"LICENSE"
],
@@ -59,21 +79,11 @@
"Utilities"
]
},
- "scripts": {
- "mocha-node-test": "mocha mocha_test/",
- "mocha-browser-test": "karma start",
- "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",
- "lint": "jshint lib/*.js test/*.js perf/*.js && jscs lib/*.js test/*.js perf/*.js",
- "coverage": "nyc npm test && nyc report",
- "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
- },
"spm": {
- "main": "lib/async.js"
+ "main": "dist/async.js"
},
"volo": {
- "main": "lib/async.js",
+ "main": "dist/async.js",
"ignore": [
"**/.*",
"node_modules",
@@ -82,4 +92,4 @@
"tests"
]
}
-}
+} \ No newline at end of file
diff --git a/support/build.test.js b/support/build.test.js
new file mode 100644
index 0000000..141909a
--- /dev/null
+++ b/support/build.test.js
@@ -0,0 +1,96 @@
+// Smoke test for the CJS build
+var methods = ["each", "waterfall", "queue", "eachSeries"];
+var expect = require('chai').expect;
+var rollup = require('rollup').rollup;
+var rollupPluginNpm = require('rollup-plugin-npm');
+var fs = require('fs');
+var exec = require('child_process').exec;
+
+describe("async main", function() {
+ var async;
+
+ before(function() {
+ async = require("../build/");
+ });
+
+ it("should have methods", function() {
+ methods.forEach(function(methodName) {
+ expect(async[methodName]).to.be.a("function");
+ });
+ });
+});
+
+describe("async umd", function() {
+ var async;
+
+ before(function() {
+ async = require("../build/dist/async.js");
+ });
+
+ it("should have methods", function() {
+ methods.forEach(function(methodName) {
+ expect(async[methodName]).to.be.a("function");
+ });
+ });
+});
+
+describe("async umd minified", function() {
+ var async;
+
+ before(function() {
+ async = require("../build/dist/async.min.js");
+ });
+
+ it("should have methods", function() {
+ methods.forEach(function(methodName) {
+ expect(async[methodName]).to.be.a("function");
+ });
+ });
+});
+
+methods.forEach(function (methodName) {
+ describe("async." + methodName, function () {
+ var method;
+ before(function () {
+ method = require("../build/" + methodName);
+ });
+
+ it("should require the individual method", function() {
+ expect(method).to.be.a("function");
+ });
+ });
+});
+
+describe("ES Modules", function () {
+ var tmpDir = __dirname + "/../tmp";
+ var buildFile = __dirname + "/../tmp/es.test.js";
+
+ before(function (done) {
+ if (fs.existsSync(tmpDir)) {
+ return done();
+ }
+ fs.mkdir(tmpDir, done);
+ });
+
+ before(function () {
+ return rollup({
+ entry: __dirname + "/es.test.js",
+ plugins: [
+ rollupPluginNpm()
+ ]
+ }).then(function (bundle) {
+ return bundle.write({
+ format: "umd",
+ dest: buildFile
+ });
+ });
+ });
+
+ it("should build a successful bundle", function (done) {
+ exec("node " + buildFile, function (err, stdout) {
+ if (err) { return done(err); }
+ expect(stdout).to.match(/42/);
+ done();
+ });
+ });
+});
diff --git a/support/build/aggregate-build.js b/support/build/aggregate-build.js
new file mode 100644
index 0000000..61833b8
--- /dev/null
+++ b/support/build/aggregate-build.js
@@ -0,0 +1,20 @@
+import compileModules from './compile-modules';
+import rollup from 'rollup';
+import rimraf from 'rimraf/rimraf';
+
+export default function buildBundle(options) {
+ function bundle() {
+ rollup.rollup({
+ entry: options.outpath + '/index.js'
+ }).then(function ( bundle ) {
+ bundle.write({
+ format: options.format,
+ moduleName: 'async',
+ dest: options.outfile
+ });
+ rimraf.sync(options.outpath);
+ }).catch(console.error);
+ }
+
+ compileModules(bundle, options);
+}
diff --git a/support/build/aggregate-bundle.js b/support/build/aggregate-bundle.js
new file mode 100644
index 0000000..482bfcd
--- /dev/null
+++ b/support/build/aggregate-bundle.js
@@ -0,0 +1,9 @@
+import aggregateBuild from './aggregate-build';
+
+aggregateBuild({
+ es6: true,
+ outpath:'build/build-modules-es6',
+ outfile: 'build/dist/async.js',
+ format: 'umd',
+ lodashRename: true
+});
diff --git a/support/build/aggregate-cjs.js b/support/build/aggregate-cjs.js
new file mode 100644
index 0000000..077ca49
--- /dev/null
+++ b/support/build/aggregate-cjs.js
@@ -0,0 +1,9 @@
+import aggregateBuild from './aggregate-build';
+
+aggregateBuild({
+ es6: true,
+ outpath:'build/build-modules-es6',
+ outfile: 'build/index.js',
+ format: 'cjs',
+ lodashRename: false
+});
diff --git a/support/build/compile-modules.js b/support/build/compile-modules.js
new file mode 100644
index 0000000..16aa1ca
--- /dev/null
+++ b/support/build/compile-modules.js
@@ -0,0 +1,45 @@
+import async from '../../lib';
+import {transformFile} from 'babel-core';
+import _ from 'lodash';
+import readdirR from 'recursive-readdir';
+import pluginCJS from 'babel-plugin-transform-es2015-modules-commonjs';
+import pluginModuleExports from 'babel-plugin-add-module-exports';
+import pluginLodashImportRename from './plugin-lodash-import-rename';
+import {join as joinPath} from 'path';
+import fs from 'fs-extra';
+
+export default function(cb, options) {
+ options = _.defaults({}, options, {
+ path:'lib/',
+ outpath:'build',
+ es6: false,
+ lodashRename: false
+ });
+ let plugins = [];
+
+ if (options.lodashRename) {
+ plugins.push(pluginLodashImportRename);
+ }
+ if (!options.es6) {
+ plugins.push(pluginModuleExports);
+ plugins.push(pluginCJS);
+ }
+
+ readdirR(options.path, [], function(err, files) {
+ fs.emptyDirSync(options.outpath);
+ fs.emptyDirSync(joinPath(options.outpath, 'internal'));
+ async.each(files, (file, callback) => {
+ let filename = file.startsWith(options.path) ?
+ file.slice(options.path.length) :
+ file;
+
+ transformFile(file, {
+ babelrc: false,
+ plugins: plugins
+ }, function(err, content) {
+ let outpath = joinPath(options.outpath, filename);
+ fs.writeFile(outpath, content.code, callback);
+ });
+ }, cb);
+ });
+}
diff --git a/support/build/modules-cjs.js b/support/build/modules-cjs.js
new file mode 100644
index 0000000..09632ff
--- /dev/null
+++ b/support/build/modules-cjs.js
@@ -0,0 +1,3 @@
+import compileModules from './compile-modules';
+
+compileModules(function() {}, {es6: false});
diff --git a/support/build/plugin-lodash-import-rename.js b/support/build/plugin-lodash-import-rename.js
new file mode 100644
index 0000000..6fe893b
--- /dev/null
+++ b/support/build/plugin-lodash-import-rename.js
@@ -0,0 +1,24 @@
+import _ from 'lodash';
+import {dirname, sep} from 'path';
+
+export default function() {
+ return {
+ visitor: {
+
+ ImportDeclaration(path, mapping) {
+ let {node} = path;
+ let {value} = node.source;
+
+ if (/\blodash\b/.test(value)) {
+ let f = mapping.file.opts.filename;
+ let dir = dirname(f).split(sep);
+ let relative = _.repeat('../', dir.length + 1);
+
+ node.source.value = value.replace(
+ /\blodash\b/,
+ relative + 'node_modules/lodash-es');
+ }
+ }
+ }
+ };
+}
diff --git a/support/es.test.js b/support/es.test.js
new file mode 100644
index 0000000..9f7fd5e
--- /dev/null
+++ b/support/es.test.js
@@ -0,0 +1,21 @@
+// simple async example to test ES module build output
+
+import {waterfall as waterfall} from "../build-es/index";
+import async from "../build-es/index";
+import constant from "../build-es/constant";
+
+waterfall([
+ constant(42),
+ function (val, next) {
+ async.setImmediate(function () {
+ next(null, val);
+ });
+ }
+], function (err, result) {
+ if (err) { throw err; }
+ console.log(result);
+ if (result !== 42) {
+ console.log("fail");
+ process.exit(1);
+ }
+});
diff --git a/support/module_template.md b/support/module_template.md
new file mode 100644
index 0000000..858f97a
--- /dev/null
+++ b/support/module_template.md
@@ -0,0 +1,13 @@
+# async.<%= name %>
+
+![Last version](https://img.shields.io/github/tag/async-js/async.<%= name %>.svg?style=flat-square)
+[![Build Status](http://img.shields.io/travis/async-js/async.<%= name %>/master.svg?style=flat-square)](https://travis-ci.org/async-js/async.<%= name %>)
+[![Dependency status](http://img.shields.io/david/async-js/async.<%= name %>.svg?style=flat-square)](https://david-dm.org/async-js/async.<%= name %>)
+[![Dev Dependencies Status](http://img.shields.io/david/dev/async-js/async.<%= name %>.svg?style=flat-square)](https://david-dm.org/async-js/async.<%= name %>#info=devDependencies)
+[![NPM Status](http://img.shields.io/npm/dm/async.<%= name %>.svg?style=flat-square)](https://www.npmjs.org/package/<%= name %>)
+
+> [async#<%= name %>](https://github.com/async-js/async#<%= name %>) method as module.
+
+## License
+
+MIT © [async-js](https://github.com/async-js)
diff --git a/support/sync-cjs-package.js b/support/sync-cjs-package.js
new file mode 100755
index 0000000..7db78b0
--- /dev/null
+++ b/support/sync-cjs-package.js
@@ -0,0 +1,10 @@
+#!/usr/bin/env node
+
+var fs = require('fs');
+var json = JSON.parse(fs.readFileSync(__dirname + "/../package.json"), "utf8");
+
+delete json.dependencies["lodash-es"];
+
+process.stdout.write(JSON.stringify(json, null, 2));
+
+
diff --git a/support/sync-es-package.js b/support/sync-es-package.js
new file mode 100755
index 0000000..bb72f47
--- /dev/null
+++ b/support/sync-es-package.js
@@ -0,0 +1,15 @@
+#!/usr/bin/env node
+
+var fs = require('fs');
+var json = JSON.parse(fs.readFileSync(__dirname + "/../package.json"), "utf8");
+
+json.name = "async-es";
+json.main = "index.js";
+delete json.dependencies["lodash"];
+delete json.volo;
+delete json.spm;
+delete json.jam;
+
+process.stdout.write(JSON.stringify(json, null, 2));
+
+
diff --git a/support/sync-package-managers.js b/support/sync-package-managers.js
index 28c22e9..d01d17c 100755
--- a/support/sync-package-managers.js
+++ b/support/sync-package-managers.js
@@ -10,40 +10,42 @@ var _ = require('lodash');
var packageJson = require('../package.json');
var IGNORES = ['**/.*', 'node_modules', 'bower_components', 'test', 'tests'];
-var INCLUDES = ['lib/async.js', 'README.md', 'LICENSE'];
+var INCLUDES = ['dist/async.js', 'README.md', 'LICENSE'];
var REPOSITORY_NAME = 'caolan/async';
packageJson.jam = {
- main: packageJson.main,
- include: INCLUDES,
- categories: ['Utilities']
+ main: packageJson.main,
+ include: INCLUDES,
+ categories: ['Utilities']
};
packageJson.spm = {
- main: packageJson.main
+ main: packageJson.main
};
packageJson.volo = {
- main: packageJson.main,
- ignore: IGNORES
+ main: packageJson.main,
+ ignore: IGNORES
};
var bowerSpecific = {
- moduleType: ['amd', 'globals', 'node'],
- ignore: IGNORES,
- authors: [packageJson.author]
+ moduleType: ['amd', 'globals', 'node'],
+ ignore: IGNORES,
+ authors: [packageJson.author]
};
var bowerInclude = ['name', 'description', 'main', 'keywords',
- 'license', 'homepage', 'repository', 'devDependencies'];
+ 'license', 'homepage', 'repository', 'devDependencies'
+];
var componentSpecific = {
- repository: REPOSITORY_NAME,
- scripts: [packageJson.main]
+ repository: REPOSITORY_NAME,
+ scripts: [packageJson.main]
};
var componentInclude = ['name', 'description', 'version', 'keywords',
- 'license', 'main'];
+ 'license', 'main'
+];
var bowerJson = _.merge({}, _.pick(packageJson, bowerInclude), bowerSpecific);
var componentJson = _.merge({}, _.pick(packageJson, componentInclude), componentSpecific);
diff --git a/support/xyz.sh b/support/xyz.sh
new file mode 100755
index 0000000..8fd8d2d
--- /dev/null
+++ b/support/xyz.sh
@@ -0,0 +1,171 @@
+#!/usr/bin/env bash
+
+# Slightly modified version of xyz that publishes from the build directory,
+# rather than the root.
+
+set -e
+
+usage="
+Usage: xyz [options]
+
+Publish a new version of the npm package in the current working directory.
+This involves updating the version number in package.json, committing this
+change (along with any staged changes), tagging the commit, pushing to the
+remote git repository, and finally publishing to the public npm registry.
+
+If present, component.json is updated along with package.json.
+
+Options:
+
+-b --branch <name>
+ Specify the branch from which new versions must be published.
+ xyz aborts if run from any other branch to prevent accidental
+ publication of feature branches. 'master' is assumed if this
+ option is omitted.
+
+-i --increment <level>
+ Specify the level of the current version number to increment.
+ Valid levels: 'major', 'minor', 'patch', 'premajor', 'preminor',
+ 'prepatch', and 'prerelease'. 'patch' is assumed if this option
+ is omitted.
+
+-m --message <template>
+ Specify the format of the commit (and tag) message.
+ 'X.Y.Z' acts as a placeholder for the version number.
+ 'Version X.Y.Z' is assumed if this option is omitted.
+
+-r --repo <repository>
+ Specify the remote repository to which to 'git push'.
+ The value must be either a URL or the name of a remote.
+ The latter is not recommended: it relies on local state.
+ 'origin' is assumed if this option is omitted.
+
+-s --script <path>
+ Specify a script to be run after the confirmation prompt.
+ It is passed VERSION and PREVIOUS_VERSION as environment
+ variables. xyz aborts if the script's exit code is not 0.
+
+-t --tag <template>
+ Specify the format of the tag name. As with --message,
+ 'X.Y.Z' acts as a placeholder for the version number.
+ 'vX.Y.Z' is assumed if this option is omitted.
+
+--dry-run
+ Print the commands without evaluating them.
+
+-v --version
+ Print xyz's version number and exit.
+"
+
+# http://stackoverflow.com/a/246128/312785
+path="${BASH_SOURCE[0]}"
+while [ -h "$path" ] ; do
+ dir="$(cd -P "$(dirname "$path")" && pwd)"
+ path="$(readlink "$path")"
+ [[ $path == /* ]] || path="$dir/$path"
+done
+dir="$(cd -P "$(dirname "$path")" && pwd)"
+
+branch=master
+increment=patch
+message_template='Version X.Y.Z'
+repo=origin
+declare -a scripts
+tag_template=vX.Y.Z
+dry_run=false
+
+while (($# > 0)) ; do
+ option="$1"
+ shift
+
+ case "$option" in
+ -h|--help)
+ echo "$usage"
+ exit
+ ;;
+ -v|--version)
+ node -p "require('$dir/package.json').version"
+ exit
+ ;;
+ -b|--branch) branch="$1" ; shift ;;
+ -i|--increment) increment="$1" ; shift ;;
+ -m|--message) message_template="$1" ; shift ;;
+ -r|--repo) repo="$1" ; shift ;;
+ -s|--script) scripts+=("$1") ; shift ;;
+ -t|--tag) tag_template="$1" ; shift ;;
+ --dry-run) dry_run=true ;;
+ *)
+ echo "Unrecognized option $option" >&2
+ exit 1
+ esac
+done
+
+case "$increment" in
+ major|minor|patch|premajor|preminor|prepatch|prerelease) ;;
+ *) echo "Invalid --increment" >&2 ; exit 1 ;;
+esac
+
+[[ $(git rev-parse --abbrev-ref HEAD) == $branch ]] ||
+ (echo "Current branch does not match specified --branch" >&2 ; exit 1)
+
+git diff-files --quiet ||
+ (echo "Working directory contains unstaged changes" >&2 ; exit 1)
+
+name=$(node -p "require('./package.json').name" 2>/dev/null) ||
+ (echo "Cannot read package name" >&2 ; exit 1)
+
+version=$(node -p "require('./package.json').version" 2>/dev/null) ||
+ (echo "Cannot read package version" >&2 ; exit 1)
+
+next_version=$("$dir/node_modules/.bin/semver" -i "$increment" "$version") ||
+ (echo "Cannot increment version number" >&2 ; exit 1)
+
+message="${message_template//X.Y.Z/$next_version}"
+tag="${tag_template//X.Y.Z/$next_version}"
+
+bold=$(tput bold)
+reset=$(tput sgr0)
+printf "Current version is ${bold}${version}${reset}. "
+printf "Press [enter] to publish ${bold}${name}@${next_version}${reset}."
+read -s # suppress user input
+echo # output \n since [enter] output was suppressed
+
+run() {
+ echo "$1"
+ if [[ $dry_run == false ]] ; then
+ eval "$1"
+ fi
+}
+
+# Prune before running tests to catch dependencies that have been
+# installed but not specified in the project's `package.json` file.
+
+run "npm prune"
+run "npm test"
+
+for script in "${scripts[@]}" ; do
+ [[ $script == /* ]] || script="$(pwd)/$script"
+ run "VERSION=$next_version PREVIOUS_VERSION=$version '$script'"
+done
+
+inc() {
+ if [[ -f "$1" ]] ; then
+ run "node -e '$(echo "
+ var o = require('./$1'); o.version = '$next_version';
+ require('fs').writeFileSync('./$1', JSON.stringify(o, null, 2) + '\n');
+ " | tr "'" '"' | tr -d "\n" | tr -s " " | sed -e "s/^ *//" -e "s/ *$//")'"
+ run "git add '$1'"
+ fi
+}
+
+inc package.json
+
+run "./sync-package-managers.js"
+run "git add --force *.json"
+
+run "git commit --message '$message'"
+run "git tag --annotate '$tag' --message '$message'"
+run "git push '$repo' 'refs/heads/$branch' 'refs/tags/$tag'"
+
+#cd build/
+#run "npm pack"
diff --git a/test/test-async.js b/test/test-async.js
index 79178ad..bd103bf 100755
--- a/test/test-async.js
+++ b/test/test-async.js
@@ -3,7 +3,8 @@
* adding a new test, consider creating a new spec file in mocha_tests/
*/
-var async = require('../lib/async');
+require('babel-core/register');
+var async = require('../lib');
if (!Function.prototype.bind) {
Function.prototype.bind = function (thisArg) {
@@ -36,19 +37,6 @@ function mapIterator(call_order, x, callback) {
}, x*25);
}
-function filterIterator(x, callback) {
- setTimeout(function(){
- callback(x % 2);
- }, x*25);
-}
-
-function detectIterator(call_order, x, callback) {
- setTimeout(function(){
- call_order.push(x);
- callback(x == 2);
- }, x*25);
-}
-
function eachNoCallbackIterator(test, x, callback) {
test.equal(x, 1);
callback();
@@ -290,641 +278,6 @@ exports['seq without callback'] = function (test) {
add2mul3.call(testcontext, 3);
};
-exports['auto'] = function(test){
- var callOrder = [];
- async.auto({
- task1: ['task2', function(callback){
- setTimeout(function(){
- callOrder.push('task1');
- callback();
- }, 25);
- }],
- task2: function(callback){
- setTimeout(function(){
- callOrder.push('task2');
- callback();
- }, 50);
- },
- task3: ['task2', function(callback){
- callOrder.push('task3');
- callback();
- }],
- task4: ['task1', 'task2', function(callback){
- callOrder.push('task4');
- callback();
- }],
- task5: ['task2', function(callback){
- setTimeout(function(){
- callOrder.push('task5');
- callback();
- }, 0);
- }],
- task6: ['task2', function(callback){
- callOrder.push('task6');
- callback();
- }]
- },
- function(err){
- test.ok(err === null, err + " passed instead of 'null'");
- test.same(callOrder, ['task2','task6','task3','task5','task1','task4']);
- test.done();
- });
-};
-
-exports['auto concurrency'] = function (test) {
- var concurrency = 2;
- var runningTasks = [];
- var makeCallback = function(taskName) {
- return function(callback) {
- runningTasks.push(taskName);
- setTimeout(function(){
- // Each task returns the array of running tasks as results.
- var result = runningTasks.slice(0);
- runningTasks.splice(runningTasks.indexOf(taskName), 1);
- callback(null, result);
- });
- };
- };
- async.auto({
- task1: ['task2', makeCallback('task1')],
- task2: makeCallback('task2'),
- task3: ['task2', makeCallback('task3')],
- task4: ['task1', 'task2', makeCallback('task4')],
- task5: ['task2', makeCallback('task5')],
- task6: ['task2', makeCallback('task6')]
- }, concurrency, function(err, results){
- Object.keys(results).forEach(function(taskName) {
- test.ok(results[taskName].length <= concurrency);
- });
- test.done();
- });
-};
-
-exports['auto petrify'] = function (test) {
- var callOrder = [];
- async.auto({
- task1: ['task2', function (callback) {
- setTimeout(function () {
- callOrder.push('task1');
- callback();
- }, 100);
- }],
- task2: function (callback) {
- setTimeout(function () {
- callOrder.push('task2');
- callback();
- }, 200);
- },
- task3: ['task2', function (callback) {
- callOrder.push('task3');
- callback();
- }],
- task4: ['task1', 'task2', function (callback) {
- callOrder.push('task4');
- callback();
- }]
- },
- function (err) {
- if (err) throw err;
- test.same(callOrder, ['task2', 'task3', 'task1', 'task4']);
- test.done();
- });
-};
-
-exports['auto results'] = function(test){
- var callOrder = [];
- async.auto({
- task1: ['task2', function(callback, results){
- test.same(results.task2, 'task2');
- setTimeout(function(){
- callOrder.push('task1');
- callback(null, 'task1a', 'task1b');
- }, 25);
- }],
- task2: function(callback){
- setTimeout(function(){
- callOrder.push('task2');
- callback(null, 'task2');
- }, 50);
- },
- task3: ['task2', function(callback, results){
- test.same(results.task2, 'task2');
- callOrder.push('task3');
- callback(null);
- }],
- task4: ['task1', 'task2', function(callback, results){
- test.same(results.task1, ['task1a','task1b']);
- test.same(results.task2, 'task2');
- callOrder.push('task4');
- callback(null, 'task4');
- }]
- },
- function(err, results){
- test.same(callOrder, ['task2','task3','task1','task4']);
- test.same(results, {task1: ['task1a','task1b'], task2: 'task2', task3: undefined, task4: 'task4'});
- test.done();
- });
-};
-
-exports['auto empty object'] = function(test){
- async.auto({}, function(err){
- test.ok(err === null, err + " passed instead of 'null'");
- test.done();
- });
-};
-
-exports['auto error'] = function(test){
- test.expect(1);
- async.auto({
- task1: function(callback){
- callback('testerror');
- },
- task2: ['task1', function(callback){
- test.ok(false, 'task2 should not be called');
- callback();
- }],
- task3: function(callback){
- callback('testerror2');
- }
- },
- function(err){
- test.equals(err, 'testerror');
- });
- setTimeout(test.done, 100);
-};
-
-exports['auto no callback'] = function(test){
- async.auto({
- task1: function(callback){callback();},
- task2: ['task1', function(callback){callback(); test.done();}]
- });
-};
-
-exports['auto concurrency no callback'] = function(test){
- async.auto({
- task1: function(callback){callback();},
- task2: ['task1', function(callback){callback(); test.done();}]
- }, 1);
-};
-
-exports['auto error should pass partial results'] = function(test) {
- async.auto({
- task1: function(callback){
- callback(false, 'result1');
- },
- task2: ['task1', function(callback){
- callback('testerror', 'result2');
- }],
- task3: ['task2', function(){
- test.ok(false, 'task3 should not be called');
- }]
- },
- function(err, results){
- test.equals(err, 'testerror');
- test.equals(results.task1, 'result1');
- test.equals(results.task2, 'result2');
- test.done();
- });
-};
-
-// Issue 24 on github: https://github.com/caolan/async/issues#issue/24
-// Issue 76 on github: https://github.com/caolan/async/issues#issue/76
-exports['auto removeListener has side effect on loop iterator'] = function(test) {
- async.auto({
- task1: ['task3', function(/*callback*/) { test.done(); }],
- task2: ['task3', function(/*callback*/) { /* by design: DON'T call callback */ }],
- task3: function(callback) { callback(); }
- });
-};
-
-// Issue 410 on github: https://github.com/caolan/async/issues/410
-exports['auto calls callback multiple times'] = function(test) {
- if (isBrowser()) {
- // node only test
- test.done();
- return;
- }
- var finalCallCount = 0;
- var domain = require('domain').create();
- domain.on('error', function (e) {
- // ignore test error
- if (!e._test_error) {
- return test.done(e);
- }
- });
- domain.run(function () {
- async.auto({
- task1: function(callback) { callback(null); },
- task2: ['task1', function(callback) { callback(null); }]
- },
-
- // Error throwing final callback. This should only run once
- function() {
- finalCallCount++;
- var e = new Error("An error");
- e._test_error = true;
- throw e;
- });
- });
- setTimeout(function () {
- test.equal(finalCallCount, 1,
- "Final auto callback should only be called once"
- );
- test.done();
- }, 10);
-};
-
-
-exports['auto calls callback multiple times with parallel functions'] = function(test) {
- test.expect(1);
- async.auto({
- task1: function(callback) { setTimeout(callback,0,"err"); },
- task2: function(callback) { setTimeout(callback,0,"err"); }
- },
- // Error throwing final callback. This should only run once
- function(err) {
- test.equal(err, "err");
- test.done();
- });
-};
-
-
-// Issue 462 on github: https://github.com/caolan/async/issues/462
-exports['auto modifying results causes final callback to run early'] = function(test) {
- async.auto({
- task1: function(callback, results){
- results.inserted = true;
- callback(null, 'task1');
- },
- task2: function(callback){
- setTimeout(function(){
- callback(null, 'task2');
- }, 50);
- },
- task3: function(callback){
- setTimeout(function(){
- callback(null, 'task3');
- }, 100);
- }
- },
- function(err, results){
- test.equal(results.inserted, true);
- test.ok(results.task3, 'task3');
- test.done();
- });
-};
-
-// Issue 263 on github: https://github.com/caolan/async/issues/263
-exports['auto prevent dead-locks due to inexistant dependencies'] = function(test) {
- test.throws(function () {
- async.auto({
- task1: ['noexist', function(callback){
- callback(null, 'task1');
- }]
- });
- }, Error);
- test.done();
-};
-
-// Issue 263 on github: https://github.com/caolan/async/issues/263
-exports['auto prevent dead-locks due to cyclic dependencies'] = function(test) {
- test.throws(function () {
- async.auto({
- task1: ['task2', function(callback){
- callback(null, 'task1');
- }],
- task2: ['task1', function(callback){
- callback(null, 'task2');
- }]
- });
- }, Error);
- test.done();
-};
-
-// Issue 988 on github: https://github.com/caolan/async/issues/988
-exports['auto stops running tasks on error'] = function(test) {
- async.auto({
- task1: function (callback) {
- callback('error');
- },
- task2: function (callback) {
- test.ok(false, 'test2 should not be called');
- callback();
- }
- }, 1, function (error) {
- test.equal(error, 'error', 'finishes with error');
- test.done();
- });
-};
-
-exports['autoInject'] = function(test){
- var callOrder = [];
- async.autoInject({
- task1: function(task2, callback){
- setTimeout(function(){
- callOrder.push('task1');
- callback();
- }, 25);
- },
- task2: function(callback){
- setTimeout(function(){
- callOrder.push('task2');
- callback();
- }, 50);
- },
- task3: function(task2, callback){
- callOrder.push('task3');
- callback();
- },
- task4: function(task1, task2, callback){
- callOrder.push('task4');
- callback();
- },
- task5: function(task2, callback){
- setTimeout(function(){
- callOrder.push('task5');
- callback();
- }, 0);
- },
- task6: function(task2, callback){
- callOrder.push('task6');
- callback();
- }
- },
- function(err){
- test.ok(err === null, err + " passed instead of 'null'");
- test.same(callOrder, ['task2','task6','task3','task5','task1','task4']);
- test.done();
- });
-};
-
-exports['autoInject concurrency'] = function (test) {
- var concurrency = 2;
- var runningTasks = [];
- var makeCallback = function(taskName) {
- return function(callback) {
- runningTasks.push(taskName);
- setTimeout(function(){
- // Each task returns the array of running tasks as results.
- var result = runningTasks.slice(0);
- runningTasks.splice(runningTasks.indexOf(taskName), 1);
- callback(null, result);
- });
- };
- };
- async.autoInject({
- task1: function(task2, callback) { makeCallback('task1')(callback); },
- task2: function(callback) { makeCallback('task2')(callback); },
- task3: function(task2, callback) { makeCallback('task3')(callback); },
- task4: function(task1, task2, callback) { makeCallback('task4')(callback); },
- task5: function(task2, callback) { makeCallback('task5')(callback); },
- task6: function(task2, callback) { makeCallback('task6')(callback); }
- }, concurrency, function(err, task1, task2, task3, task4, task5, task6){
- test.ok(task1.length <= concurrency);
- test.ok(task2.length <= concurrency);
- test.ok(task3.length <= concurrency);
- test.ok(task4.length <= concurrency);
- test.ok(task5.length <= concurrency);
- test.ok(task6.length <= concurrency);
- test.done();
- });
-};
-
-exports['autoInject petrify'] = function (test) {
- var callOrder = [];
- async.autoInject({
- task1: function (task2, callback) {
- setTimeout(function () {
- callOrder.push('task1');
- callback();
- }, 100);
- },
- task2: function (callback) {
- setTimeout(function () {
- callOrder.push('task2');
- callback();
- }, 200);
- },
- task3: function (task2, callback) {
- callOrder.push('task3');
- callback();
- },
- task4: function (task1, task2, callback) {
- callOrder.push('task4');
- callback();
- }
- },
- function (err) {
- if (err) throw err;
- test.same(callOrder, ['task2', 'task3', 'task1', 'task4']);
- test.done();
- });
-};
-
-exports['autoInject results'] = function(test){
- var callOrder = [];
- async.autoInject({
- task1: function(task2, callback){
- test.same(task2, 'task2');
- setTimeout(function(){
- callOrder.push('task1');
- callback(null, 'task1a', 'task1b');
- }, 25);
- },
- task2: function(callback){
- setTimeout(function(){
- callOrder.push('task2');
- callback(null, 'task2');
- }, 50);
- },
- task3: function(task2, callback){
- test.same(task2, 'task2');
- callOrder.push('task3');
- callback(null);
- },
- task4: function(task1, task2, callback){
- test.same(task1, ['task1a','task1b']);
- test.same(task2, 'task2');
- callOrder.push('task4');
- callback(null, 'task4');
- }
- },
- function(err, task1, task2, task3, task4){
- test.same(callOrder, ['task2','task3','task1','task4']);
- test.same(task1, ['task1a','task1b']);
- test.same(task2, 'task2');
- test.same(task3, undefined);
- test.same(task4, 'task4');
- test.done();
- });
-};
-
-exports['autoInject empty object'] = function(test){
- async.autoInject({}, function(err){
- test.ok(err === null, err + " passed instead of 'null'");
- test.done();
- });
-};
-
-exports['autoInject error'] = function(test){
- test.expect(1);
- async.autoInject({
- task1: function(callback){
- callback('testerror');
- },
- task2: function(task1, callback){
- test.ok(false, 'task2 should not be called');
- callback();
- },
- task3: function(callback){
- callback('testerror2');
- }
- },
- function(err){
- test.equals(err, 'testerror');
- });
- setTimeout(test.done, 100);
-};
-
-exports['autoInject no callback'] = function(test){
- async.autoInject({
- task1: function(callback){callback();},
- task2: function(task1, callback){callback(); test.done();}
- });
-};
-
-exports['autoInject concurrency no callback'] = function(test){
- async.autoInject({
- task1: function(callback){callback();},
- task2: function(task1, callback){callback(); test.done();}
- }, 1);
-};
-
-exports['autoInject error should pass partial results'] = function(test) {
- async.autoInject({
- task1: function(callback){
- callback(false, 'result1');
- },
- task2: function(task1, callback){
- callback('testerror', 'result2');
- },
- task3: function(task2, callback){
- test.ok(false, 'task3 should not be called');
- }
- },
- function(err, task1, task2){
- test.equals(err, 'testerror');
- test.equals(task1, 'result1');
- test.equals(task2, 'result2');
- test.done();
- });
-};
-
-// Issue 24 on github: https://github.com/caolan/async/issues#issue/24
-// Issue 76 on github: https://github.com/caolan/async/issues#issue/76
-exports['autoInject removeListener has side effect on loop iterator'] = function(test) {
- async.autoInject({
- task1: function(task3, callback) { test.done(); },
- task2: function(task3, callback) { /* by design: DON'T call callback */ },
- task3: function(callback) { callback(); }
- });
-};
-
-// Issue 410 on github: https://github.com/caolan/async/issues/410
-exports['autoInject calls callback multiple times'] = function(test) {
- if (isBrowser()) {
- // node only test
- test.done();
- return;
- }
- var finalCallCount = 0;
- var domain = require('domain').create();
- domain.on('error', function (e) {
- // ignore test error
- if (!e._test_error) {
- return test.done(e);
- }
- });
- domain.run(function () {
- async.autoInject({
- task1: function(callback) { callback(null); },
- task2: function(task1, callback) { callback(null); }
- },
-
- // Error throwing final callback. This should only run once
- function() {
- finalCallCount++;
- var e = new Error("An error");
- e._test_error = true;
- throw e;
- });
- });
- setTimeout(function () {
- test.equal(finalCallCount, 1,
- "Final auto callback should only be called once"
- );
- test.done();
- }, 10);
-};
-
-
-exports['autoInject calls callback multiple times with parallel functions'] = function(test) {
- test.expect(1);
- async.autoInject({
- task1: function(callback) { setTimeout(callback,0,"err"); },
- task2: function(callback) { setTimeout(callback,0,"err"); }
- },
- // Error throwing final callback. This should only run once
- function(err) {
- test.equal(err, "err");
- test.done();
- });
-};
-
-
-// Issue 263 on github: https://github.com/caolan/async/issues/263
-exports['autoInject prevent dead-locks due to inexistant dependencies'] = function(test) {
- test.throws(function () {
- async.autoInject({
- task1: function(noexist, callback){
- callback(null, 'task1');
- }
- });
- }, Error);
- test.done();
-};
-
-// Issue 263 on github: https://github.com/caolan/async/issues/263
-exports['autoInject prevent dead-locks due to cyclic dependencies'] = function(test) {
- test.throws(function () {
- async.autoInject({
- task1: function(task2, callback){
- callback(null, 'task1');
- },
- task2: function(task1, callback){
- callback(null, 'task2');
- }
- });
- }, Error);
- test.done();
-};
-
-// Issue 988 on github: https://github.com/caolan/async/issues/988
-exports['autoInject stops running tasks on error'] = function(test) {
- async.autoInject({
- task1: function (callback) {
- callback('error');
- },
- task2: function (callback) {
- test.ok(false, 'test2 should not be called');
- callback();
- }
- }, 1, function (error) {
- test.equal(error, 'error', 'finishes with error');
- test.done();
- });
-};
-
// Issue 306 on github: https://github.com/caolan/async/issues/306
exports['retry when attempt succeeds'] = function(test) {
var failed = 3;
@@ -996,26 +349,29 @@ exports['retry with interval when all attempts succeeds'] = function(test) {
});
};
+// need to fix retry, this isn't working
+/*
exports['retry as an embedded task'] = function(test) {
var retryResult = 'RETRY';
var fooResults;
var retryResults;
async.auto({
- foo: function(callback, results){
+ dep: async.constant('dep'),
+ foo: ['dep', function(results, callback){
fooResults = results;
callback(null, 'FOO');
- },
- retry: async.retry(function(callback, results) {
+ }],
+ retry: ['dep', async.retry(function(results, callback) {
retryResults = results;
callback(null, retryResult);
- })
+ })]
}, function(err, results){
test.equal(results.retry, retryResult, "Incorrect result was returned from retry function");
test.equal(fooResults, retryResults, "Incorrect results were passed to retry function");
test.done();
});
-};
+};*/
exports['retry as an embedded task with interval'] = function(test) {
var start = new Date().getTime();
@@ -1642,9 +998,10 @@ exports['each extra callback'] = function(test){
var count = 0;
async.each([1,3,2], function(val, callback) {
count++;
+ var done = count == 3;
callback();
test.throws(callback);
- if (count == 3) {
+ if (done) {
test.done();
}
});
@@ -2165,8 +1522,9 @@ exports['map'] = {
var r = [];
async.map(a, function(x, callback){
r.push(x);
+ var done = r.length == a.length;
callback(null);
- if (r.length >= a.length) {
+ if (done) {
test.same(r, a);
test.done();
}
@@ -2466,349 +1824,6 @@ exports['transform error'] = function(test){
});
};
-exports['filter'] = function(test){
- async.filter([3,1,2], filterIterator, function(results){
- test.same(results, [3,1]);
- test.done();
- });
-};
-
-exports['filter original untouched'] = function(test){
- var a = [3,1,2];
- async.filter(a, function(x, callback){
- callback(x % 2);
- }, function(results){
- test.same(results, [3,1]);
- test.same(a, [3,1,2]);
- test.done();
- });
-};
-
-exports['filterSeries'] = function(test){
- async.filterSeries([3,1,2], filterIterator, function(results){
- test.same(results, [3,1]);
- test.done();
- });
-};
-
-exports['select alias'] = function(test){
- test.equals(async.select, async.filter);
- test.done();
-};
-
-exports['selectSeries alias'] = function(test){
- test.equals(async.selectSeries, async.filterSeries);
- test.done();
-};
-
-exports['reject'] = function(test){
- test.expect(1);
- async.reject([3,1,2], filterIterator, function(results){
- test.same(results, [2]);
- test.done();
- });
-};
-
-exports['reject original untouched'] = function(test){
- test.expect(2);
- var a = [3,1,2];
- async.reject(a, function(x, callback){
- callback(x % 2);
- }, function(results){
- test.same(results, [2]);
- test.same(a, [3,1,2]);
- test.done();
- });
-};
-
-exports['rejectSeries'] = function(test){
- test.expect(1);
- async.rejectSeries([3,1,2], filterIterator, function(results){
- test.same(results, [2]);
- test.done();
- });
-};
-
-function testLimit(test, arr, limitFunc, limit, iter, done) {
- var args = [];
-
- limitFunc(arr, limit, function(x) {
- args.push(x);
- iter.apply(this, arguments);
- }, function() {
- test.same(args, arr);
- if (done) done.apply(this, arguments);
- else test.done();
- });
-}
-
-exports['rejectLimit'] = function(test) {
- test.expect(2);
- testLimit(test, [5, 4, 3, 2, 1], async.rejectLimit, 2, function(v, next) {
- next(v % 2);
- }, function(x) {
- test.same(x, [4, 2]);
- test.done();
- });
-};
-
-exports['filterLimit'] = function(test) {
- test.expect(2);
- testLimit(test, [5, 4, 3, 2, 1], async.filterLimit, 2, function(v, next) {
- next(v % 2);
- }, function(x) {
- test.same(x, [5, 3, 1]);
- test.done();
- });
-};
-
-exports['some true'] = function(test){
- test.expect(1);
- async.some([3,1,2], function(x, callback){
- setTimeout(function(){callback(x === 1);}, 0);
- }, function(result){
- test.equals(result, true);
- test.done();
- });
-};
-
-exports['some false'] = function(test){
- test.expect(1);
- async.some([3,1,2], function(x, callback){
- setTimeout(function(){callback(x === 10);}, 0);
- }, function(result){
- test.equals(result, false);
- test.done();
- });
-};
-
-exports['some early return'] = function(test){
- test.expect(1);
- var call_order = [];
- async.some([1,2,3], function(x, callback){
- setTimeout(function(){
- call_order.push(x);
- callback(x === 1);
- }, x*25);
- }, function(){
- call_order.push('callback');
- });
- setTimeout(function(){
- test.same(call_order, [1,'callback',2,3]);
- test.done();
- }, 100);
-};
-
-exports['someLimit true'] = function(test){
- async.someLimit([3,1,2], 2, function(x, callback){
- setTimeout(function(){callback(x === 2);}, 0);
- }, function(result){
- test.equals(result, true);
- test.done();
- });
-};
-
-exports['someLimit false'] = function(test){
- async.someLimit([3,1,2], 2, function(x, callback){
- setTimeout(function(){callback(x === 10);}, 0);
- }, function(result){
- test.equals(result, false);
- test.done();
- });
-};
-
-exports['every true'] = function(test){
- async.everyLimit([3,1,2], 1, function(x, callback){
- setTimeout(function(){callback(x > 1);}, 0);
- }, function(result){
- test.equals(result, true);
- test.done();
- });
-};
-
-exports['everyLimit false'] = function(test){
- async.everyLimit([3,1,2], 2, function(x, callback){
- setTimeout(function(){callback(x === 2);}, 0);
- }, function(result){
- test.equals(result, false);
- test.done();
- });
-};
-
-exports['everyLimit short-circuit'] = function(test){
- test.expect(2);
- var calls = 0;
- async.everyLimit([3,1,2], 1, function(x, callback){
- calls++;
- callback(x === 1);
- }, function(result){
- test.equals(result, false);
- test.equals(calls, 1);
- test.done();
- });
-};
-
-
-exports['someLimit short-circuit'] = function(test){
- test.expect(2);
- var calls = 0;
- async.someLimit([3,1,2], 1, function(x, callback){
- calls++;
- callback(x === 1);
- }, function(result){
- test.equals(result, true);
- test.equals(calls, 2);
- test.done();
- });
-};
-
-exports['any alias'] = function(test){
- test.equals(async.any, async.some);
- test.done();
-};
-
-exports['every true'] = function(test){
- test.expect(1);
- async.every([1,2,3], function(x, callback){
- setTimeout(function(){callback(true);}, 0);
- }, function(result){
- test.equals(result, true);
- test.done();
- });
-};
-
-exports['every false'] = function(test){
- test.expect(1);
- async.every([1,2,3], function(x, callback){
- setTimeout(function(){callback(x % 2);}, 0);
- }, function(result){
- test.equals(result, false);
- test.done();
- });
-};
-
-exports['every early return'] = function(test){
- test.expect(1);
- var call_order = [];
- async.every([1,2,3], function(x, callback){
- setTimeout(function(){
- call_order.push(x);
- callback(x === 1);
- }, x*25);
- }, function(){
- call_order.push('callback');
- });
- setTimeout(function(){
- test.same(call_order, [1,2,'callback',3]);
- test.done();
- }, 100);
-};
-
-exports['all alias'] = function(test){
- test.equals(async.all, async.every);
- test.done();
-};
-
-exports['detect'] = function(test){
- test.expect(2);
- var call_order = [];
- async.detect([3,2,1], detectIterator.bind(this, call_order), function(result){
- call_order.push('callback');
- test.equals(result, 2);
- });
- setTimeout(function(){
- test.same(call_order, [1,2,'callback',3]);
- test.done();
- }, 100);
-};
-
-exports['detect - mulitple matches'] = function(test){
- test.expect(2);
- var call_order = [];
- async.detect([3,2,2,1,2], detectIterator.bind(this, call_order), function(result){
- call_order.push('callback');
- test.equals(result, 2);
- });
- setTimeout(function(){
- test.same(call_order, [1,2,'callback',2,2,3]);
- test.done();
- }, 100);
-};
-
-exports['detectSeries'] = function(test){
- test.expect(2);
- var call_order = [];
- async.detectSeries([3,2,1], detectIterator.bind(this, call_order), function(result){
- call_order.push('callback');
- test.equals(result, 2);
- });
- setTimeout(function(){
- test.same(call_order, [3,2,'callback']);
- test.done();
- }, 200);
-};
-
-exports['detectSeries - multiple matches'] = function(test){
- test.expect(2);
- var call_order = [];
- async.detectSeries([3,2,2,1,2], detectIterator.bind(this, call_order), function(result){
- call_order.push('callback');
- test.equals(result, 2);
- });
- setTimeout(function(){
- test.same(call_order, [3,2,'callback']);
- test.done();
- }, 200);
-};
-
-exports['detectSeries - ensure stop'] = function (test) {
- test.expect(1);
- async.detectSeries([1, 2, 3, 4, 5], function (num, cb) {
- if (num > 3) throw new Error("detectSeries did not stop iterating");
- cb(num === 3);
- }, function (result) {
- test.equals(result, 3);
- test.done();
- });
-};
-
-exports['detectLimit'] = function(test){
- test.expect(2);
- var call_order = [];
- async.detectLimit([3, 2, 1], 2, detectIterator.bind(this, call_order), function(result) {
- call_order.push('callback');
- test.equals(result, 2);
- });
- setTimeout(function() {
- test.same(call_order, [2, 'callback', 3]);
- test.done();
- }, 100);
-};
-
-exports['detectLimit - multiple matches'] = function(test){
- test.expect(2);
- var call_order = [];
- async.detectLimit([3,2,2,1,2], 2, detectIterator.bind(this, call_order), function(result){
- call_order.push('callback');
- test.equals(result, 2);
- });
- setTimeout(function(){
- test.same(call_order, [2, 'callback', 3]);
- test.done();
- }, 100);
-};
-
-exports['detectLimit - ensure stop'] = function (test) {
- test.expect(1);
- async.detectLimit([1, 2, 3, 4, 5], 2, function (num, cb) {
- if (num > 4) throw new Error("detectLimit did not stop iterating");
- cb(num === 3);
- }, function (result) {
- test.equals(result, 3);
- test.done();
- });
-};
-
exports['sortBy'] = function(test){
test.expect(2);
@@ -3055,37 +2070,6 @@ exports['nextTick in the browser'] = function(test){
setTimeout(test.done, 100);
};
-exports['noConflict - node only'] = function(test){
- if (!isBrowser()) {
- // node only test
- test.expect(3);
- var fs = require('fs');
- var vm = require('vm');
- var filename = __dirname + '/../lib/async.js';
- fs.readFile(filename, function(err, content){
- if(err) return test.done();
-
- var s = vm.createScript(content, filename);
- var s2 = vm.createScript(
- content + 'this.async2 = this.async.noConflict();',
- filename
- );
-
- var sandbox1 = {async: 'oldvalue'};
- s.runInNewContext(sandbox1);
- test.ok(sandbox1.async);
-
- var sandbox2 = {async: 'oldvalue'};
- s2.runInNewContext(sandbox2);
- test.equals(sandbox2.async, 'oldvalue');
- test.ok(sandbox2.async2);
-
- test.done();
- });
- }
- else test.done();
-};
-
exports['concat'] = function(test){
test.expect(3);
var call_order = [];
@@ -4617,6 +3601,53 @@ exports['memoize'] = {
test.equal(val, "bar");
test.done();
});
+},
+
+ 'avoid constructor key return undefined': function (test) {
+ test.expect(1);
+ var fn = async.memoize(function(name, callback) {
+ setTimeout(function(){
+ callback(null, name);
+ }, 100);
+ });
+ fn('constructor', function(error, results) {
+ test.equal(results, 'constructor');
+ test.done();
+ });
+},
+
+ 'avoid __proto__ key return undefined': function (test) {
+ // Skip test if there is a Object.create bug (node 0.10 and some Chrome 30x versions)
+ var x = Object.create(null);
+ /* jshint proto: true */
+ x.__proto__ = 'foo';
+ if (x.__proto__ !== 'foo') {
+ return test.done();
+ }
+
+ test.expect(1);
+ var fn = async.memoize(function(name, callback) {
+ setTimeout(function(){
+ callback(null, name);
+ }, 100);
+ });
+ fn('__proto__', function(error, results) {
+ test.equal(results, '__proto__');
+ test.done();
+ });
+},
+
+ 'allow hasOwnProperty as key': function (test) {
+ test.expect(1);
+ var fn = async.memoize(function(name, callback) {
+ setTimeout(function(){
+ callback(null, name);
+ }, 100);
+ });
+ fn('hasOwnProperty', function(error, results) {
+ test.equal(results, 'hasOwnProperty');
+ test.done();
+ });
}
};
diff --git a/test/test.html b/test/test.html
index 2450e2d..0047af4 100644
--- a/test/test.html
+++ b/test/test.html
@@ -6,7 +6,7 @@
the async lib internally and will overwrite the version we want to test
-->
<script src="../deps/nodeunit.js"></script>
- <script src="../lib/async.js"></script>
+ <script src="../dist/async.js"></script>
<link rel="stylesheet" href="../deps/nodeunit.css" type="text/css" media="screen" />
<script>
var _async = this.async;