diff --git a/src/Q.ts b/src/Q.ts index bf4d0959..62367090 100644 --- a/src/Q.ts +++ b/src/Q.ts @@ -1,47 +1,54 @@ -type QChild = { - type: "child"; - funcs: Array | QChild>; -}; +type QChild = + | { type: "child"; funcs: Array } + | ((context: any, next: () => void) => void); -export default function Q( - funcs: Array | QChild>, - c?: any, - done?: Function -) { - const context = c || {}; - let idx = 0; +type QFunc = Function | Array | QChild; - (function next() { - if (!funcs[idx]) { - if (done) { - done(context); - } - return; - } - if (Array.isArray(funcs[idx])) { - funcs.splice( - idx, - 1, - ...(funcs[idx][0](context) ? funcs[idx][1] : funcs[idx][2]) - ); - next(); - } else { - // console.log(funcs[idx].name + " / " + JSON.stringify(context)); - // console.log(funcs[idx].name); - (funcs[idx] as Function)(context, (moveForward) => { - if (typeof moveForward === "undefined" || moveForward === true) { - idx += 1; - next(); - } else if (done) { +type QOptions = { + context?: any; + done?: Function; +}; + + export default function Q(funcs: Array, options: QOptions) { + const context = options.context || {}; + const done = options.done; + let idx = 0; + + (function next() { + const currentFunc = funcs[idx]; + if (!currentFunc) { + if (done) { done(context); } - }); - } - })(); -} - -Q.if = function (condition: Function, one, two) { - if (!Array.isArray(one)) one = [one]; - if (!Array.isArray(two)) two = [two]; - return [condition, one, two]; + return; + } + if (Array.isArray(currentFunc)) { + const [conditionFn, truthyFuncs, falsyFuncs] = currentFunc; + funcs.splice( + idx, + 1, + ...(conditionFn(context) ? truthyFuncs : falsyFuncs) + ); + next(); + } else { + // console.log(funcs[idx].name + " / " + JSON.stringify(context)); + // console.log(funcs[idx].name); + // console.log(currentFunc.name + " / " + JSON.stringify(context)); + // console.log(currentFunc.name); + (currentFunc as Function)(context, (moveForward) => { + if (typeof moveForward === "undefined" || moveForward === true) { + idx += 1; + next(); + } else if (done) { + done(context); + } + }); + } + })(); + } + +Q.if = function (condition: Function, truthyFuncs, falsyFuncs) { + if (!Array.isArray(truthyFuncs)) truthyFuncs = [truthyFuncs]; + if (!Array.isArray(falsyFuncs)) falsyFuncs = [falsyFuncs]; + return [condition, truthyFuncs, falsyFuncs]; };