第 56 题:要求设计 LazyMan 类,实现以下功能。
LazyMan("Tony"); // Hi I am Tony LazyMan("Tony") .sleep(10) .eat("lunch"); // Hi I am Tony // 等待了10秒... // I am eating lunch LazyMan("Tony") .eat("lunch") .sleep(10) .eat("dinner"); // Hi I am Tony // I am eating lunch // 等待了10秒... // I am eating diner LazyMan("Tony") .eat("lunch") .eat("dinner") .sleepFirst(5) .sleep(10) .eat("junk food"); // Hi I am Tony // 等待了5秒... // I am eating lunch // I am eating dinner // 等待了10秒... // I am eating junk food
发现了网上的答案有个漏洞,只能在最开始的触发,所以我的版本里面通过proxy对事件列表数组进行监控,通过这样在数组改变的时候触发改变。
class LazyManClass {
name: string;
events: ((data?: string) => void)[];
timer: boolean;
constructor(name: string) {
this.name = name;
this.timer = false;
let that = this;
this.events = new Proxy([], {
set(target: any, p, value, receiver) {
target[p] = value;
if (that.timer === true) {
that.timer = false;
that.run();
}
return true;
},
});
console.log("Hi i am " + this.name);
this.run();
}
run() {
let that = this;
if (!that.timer) {
setTimeout(() => {
that.next();
}, 0);
}
}
next() {
let fn = this.events.shift();
fn ? fn() : (this.timer = true);
}
sleep(value: number) {
const that = this;
const fn = () =>
setTimeout(() => {
console.log("等待了多少秒");
that.next();
}, 1000 * value);
this.events.push(fn);
return this;
}
sleepFirst(value: number) {
const that = this;
const fn = () =>
setTimeout(() => {
console.log("先等待了多少秒");
that.next();
}, 1000 * value);
this.events.unshift(fn);
return this;
}
eatLunch() {
const that = this;
this.events.push(() => {
console.log("eat lunch");
that.next();
});
return this;
}
eatBreakfast() {
const that = this;
this.events.push(() => {
console.log("eat breakfast");
that.next();
});
return this;
}
eatDinner() {
const that = this;
this.events.push(() => {
console.log("eat dinner");
that.next();
});
return this;
}
}
const LazyMan = function (name: string) {
return new LazyManClass(name);
};
let man = LazyMan("ceshi");
man.eatBreakfast().eatDinner().sleepFirst(1).sleep(3).eatBreakfast();
window.onclick=()=>{
man.eatBreakfast().eatDinner().sleepFirst(1).sleep(3).eatBreakfast();
}