summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorAlexander Early <alexander.early@gmail.com>2016-03-08 16:17:25 -0800
committerAlexander Early <alexander.early@gmail.com>2016-03-08 16:17:25 -0800
commit27230c22ccc567f7944b0dc7be23148c5e7304b0 (patch)
treeea3656e4554d8b4039aa9ec7d9837b2ff94b55a6 /lib
parentf6a19cec4dae3afd3dfb53d07baabd88ce282b5c (diff)
downloadasync-27230c22ccc567f7944b0dc7be23148c5e7304b0.tar.gz
added autoInject, adapted from #608
Diffstat (limited to 'lib')
-rw-r--r--lib/autoInject.js45
-rw-r--r--lib/index.js3
2 files changed, 48 insertions, 0 deletions
diff --git a/lib/autoInject.js b/lib/autoInject.js
new file mode 100644
index 0000000..1b6fea4
--- /dev/null
+++ b/lib/autoInject.js
@@ -0,0 +1,45 @@
+import auto from './auto';
+import forOwn from 'lodash/forOwn';
+import arrayMap from 'lodash/_arrayMap';
+import isArray from 'lodash/isArray';
+
+var argsRegex = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
+
+function parseParams(func) {
+ return func.toString().match(argsRegex)[1].split(/\s*\,\s*/);
+}
+
+export default function autoInject(tasks, callback) {
+ var newTasks = {};
+
+ forOwn(tasks, function (taskFn, key) {
+ var params;
+
+ if (isArray(taskFn)) {
+ params = [...taskFn];
+ taskFn = params.pop();
+
+ newTasks[key] = [...params].concat(newTask);
+ } else if (taskFn.length === 0) {
+ throw new Error("autoInject task functions require explicit parameters.");
+ } else if (taskFn.length === 1) {
+ // no dependencies
+ newTasks[key] = taskFn;
+ } else {
+ params = parseParams(taskFn);
+ params.pop();
+
+ newTasks[key] = [...params].concat(newTask);
+
+ }
+
+ function newTask(results, taskCb) {
+ var newArgs = arrayMap(params, function (name) {
+ return results[name];
+ });
+ taskFn(...newArgs.concat(taskCb));
+ }
+ });
+
+ auto(newTasks, callback);
+}
diff --git a/lib/index.js b/lib/index.js
index 300491d..3db4064 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -5,6 +5,7 @@ import applyEachSeries from './applyEachSeries';
import apply from './apply';
import asyncify from './asyncify';
import auto from './auto';
+import autoInject from './autoInject';
import cargo from './cargo';
import compose from './compose';
import concat from './concat';
@@ -71,6 +72,7 @@ export default {
apply: apply,
asyncify: asyncify,
auto: auto,
+ autoInject: autoInject,
cargo: cargo,
compose: compose,
concat: concat,
@@ -155,6 +157,7 @@ export {
apply as apply,
asyncify as asyncify,
auto as auto,
+ autoInject as autoInject,
cargo as cargo,
compose as compose,
concat as concat,