Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 49 additions & 42 deletions src/Q.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,54 @@
type QChild = {
type: "child";
funcs: Array<Function | Array<any> | QChild>;
};
type QChild =
| { type: "child"; funcs: Array<QFunc> }
| ((context: any, next: () => void) => void);

export default function Q(
funcs: Array<Function | Array<any> | QChild>,
c?: any,
done?: Function
) {
const context = c || {};
let idx = 0;
type QFunc = Function | Array<any> | 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<QFunc>, 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];
};