Define a task function and the output after execution is as follows
task('james')
// james starts work
task('james').waitFirst(5).do('push')
// wait 5s, james do push, james starts work
task('james').wait(5).do('commit')
// james starts work, wait 5s, james do commit
I have no idea how to create such a wait function, does anyone can help me about that or give me some ideas.
Here is my solution with a little annoying .end() call after every task() call.
function task(name) {
const register = {};
const preventCallAfter = (methodName) => {
if (methodName in register)
throw new Error(`You cannot use "wait" and "waitFirst" together.`);
};
return {
wait(seconds) {
preventCallAfter("waitFirst");
register.wait = seconds;
return this;
},
waitFirst(seconds) {
preventCallAfter("wait");
register.waitFirst = seconds;
return this;
},
do(workName) {
if ("workName" in register)
throw new Error(`The .do() method is already called.`);
register.workName = workName;
return this;
},
end() {
if ("wait" in register) {
console.log(`${name} starts work.`);
console.log(`wait ${register.wait} seconds.`);
setTimeout(
() => console.log(`${name} do ${register.workName}`),
register.wait * 1000
);
} else if ("waitFirst" in register) {
console.log(`wait ${register.waitFirst} seconds.`);
setTimeout(() => {
console.log(`${name} do ${register.workName}`);
console.log(`${name} starts work.`);
}, register.waitFirst * 1000);
} else console.log(`${name} starts work.`);
},
};
}
// task("james").end();
// james starts work
// task("james").waitFirst(5).do("push").end();
// wait 5s, chenlee do push, james starts work
task("james").wait(5).do("commit").end();
// james starts work, wait 5s, james do commit