-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lazyman.ts
60 lines (53 loc) · 1.64 KB
/
Lazyman.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
type Action =
| { type: "sleep"; sec: number }
| { type: "eat"; food: string }
| { type: "greet"; name: string };
const sleep = (sec: number) => {
// function should for sleeping
return new Promise((res) => {
setTimeout(res, sec * 1000);
});
};
function LazyMan(name: string, log: (arg0: string) => void) {
const actions: Action[] = []; // Array which will store all our actions
actions.push({ type: "greet", name });
const exec = async () => {
while (actions.length !== 0) {
const actionToPerform = actions.shift();
if (actionToPerform) {
switch (actionToPerform.type) {
case "greet":
log(`Hi, I'm ${actionToPerform.name}.`);
break;
case "eat":
log(`Eat ${actionToPerform.food}.`);
break;
case "sleep":
await sleep(actionToPerform.sec);
log(
`Wake up after ${actionToPerform.sec} ${
actionToPerform.sec === 1 ? "second" : "seconds"
}.`
);
break;
}
}
}
};
Promise.resolve().then(() => exec()); //We do not want to start executing until we have all information.
//By above method we are creating that delay. so we will not start executing until we have all information
return {
eat(food: string) {
actions.push({ type: "eat", food });
return this;
},
sleepFirst(sec: number) {
actions.unshift({ type: "sleep", sec }); // we have to sleep first so add sleep in front of array
return this;
},
sleep(sec: number) {
actions.push({ type: "sleep", sec });
return this;
},
};
}