-
Notifications
You must be signed in to change notification settings - Fork 1
/
LazyMan.js
99 lines (88 loc) · 1.8 KB
/
LazyMan.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
实现一个LazyMan,可以按照以下方式调用:
LazyMan("Hank")输出:
Hi! This is Hank!
done
LazyMan("Hank").sleep(10).eat("dinner")输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~
done
LazyMan("Hank").eat("dinner").eat("supper")输出
Hi This is Hank!
Eat dinner~
Eat supper~
done
LazyMan("Hank").sleepFirst(5).eat("supper")输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
以此类推。
*/
class LazyMan {
tasks = [];
constructor(name) {
this.name = name;
// this.say();
// this.tasks.push(this.say);
// this.pushTask(() => this.say)
this.say();
// this.run();
setTimeout(() => {
this.run();
}, 0);
}
say() {
this.pushTask((cb) => {
console.log(`Hi! This is ${this.name}`);
cb && cb();
});
// this.run();
return this;
}
eat(food) {
this.pushTask((cb) => {
console.log(`Eat ${food}~`);
cb && cb();
});
// this.run();
return this;
}
sleep(time) {
this.pushTask((cb) => {
setTimeout(() => {
console.log(`Wake up after ${time}`);
cb && cb();
}, time * 1000);
});
// this.run();
return this;
}
sleepFirst(time) {
this.unshiftTask((cb) => {
setTimeout(() => {
console.log(`Wake up after ${time}`);
cb && cb();
}, time * 1000);
});
return this;
}
run() {
// this.tasks.forEach((task) => task());
if (this.tasks.length > 0) {
const task = this.tasks.shift();
task(() => this.run());
}
}
pushTask(newTask) {
this.tasks.push(newTask);
}
unshiftTask(newTask) {
this.tasks.unshift(newTask);
}
}
console.log(new LazyMan('Hank').sleepFirst(5).eat('supper'));