手写链式调用

遇到一个有趣的题目,做个笔记

实现一个arrange函数,可以进行时间和工作调度
//[> …]表示调用函数后的打印内容

//arrange(‘William’).execute();
//> William is notified

//arrange(‘William’).do(‘commit’).execute();
//>William is notified
//>Start to commit

//arrange(‘William’).wait(5).do(‘commit’).execute();
//>William is notified
//等待5秒
//>Start to commit

//arrange(‘William’).waitFirst(5).do(‘push’).execute();
//等待5秒
//>William is notifed
//>Start to push

function arrange(){
//此处写代码逻辑
}

可以通过链式调用来实现这个问题。每个方法都返回一个对象,该对象包含当前的状态和一系列要执行的方法

function arrange(name) {
  const state = {
    name: name,
    actions: [],
    waitFirstTime: 0
  };

  return {
    execute() {
      if (state.waitFirstTime > 0) {
        setTimeout(() => this.executeAfterWait(), state.waitFirstTime * 1000);
      } else {
        this.executeAfterWait();
      }
    },
    executeAfterWait() {
      console.log(`${state.name} is notified`);
      state.actions.forEach(action => {
        if (action.type === 'wait') {
          setTimeout(action.fn, action.time * 1000);
        } else {
          action.fn();
        }
      });
    },
    do(task) {
      state.actions.push({
        type: 'task',
        fn: () => console.log(`Start to ${task}`)
      });
      return this;
    },
    wait(time) {
      state.actions.push({
        type: 'wait',
        time: time,
        fn: () => console.log(`Waited for ${time} seconds`)
      });
      return this;
    },
    waitFirst(time) {
      state.waitFirstTime = time;
      return this;
    }
  };
}

// 测试用例
arrange('William').execute();
arrange('William').do('commit').execute();
arrange('William').wait(5).do('commit').execute();
arrange('William').waitFirst(5).do('push').execute();

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值