Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More readable and understandable #327

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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];
};