LazyMan试题

 第 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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值