当前位置: 首页 > news >正文

手写链式调用

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

实现一个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();
http://www.lryc.cn/news/136837.html

相关文章:

  • DETRs with Collaborative Hybrid Assignments Training论文笔记
  • 慧程HiperM3系列工业物联网、MES平台
  • SHELL 基础 入门(三) Bash 快捷键 命令执行顺序,详解通配符
  • nvm安装使用教程
  • 【Android】JUnit和Espresso单元测试新手快速入门
  • 8.4 【C语言】通过指针引用字符串
  • 【广州华锐视点】AR配电所巡检系统:可视化巡检利器
  • 微服务中间件--http客户端Feign
  • C语言学习系列-->【关于qsort函数的详解以及它的模拟实现】
  • Linux系统安全:NAT(SNAT、DNAT)
  • 【数据库】MySQL存储过程:提升数据库性能和操作效率的利器
  • rust写一个多线程和协程的例子
  • react18+antd5.x(1):Notification组件的二次封装
  • jenkins运行pytest测试用例脚本报错:没有权限,无法写日志PermissionError:[Error 13]Permission denied
  • 数据结构 day1
  • 湖北咸宁农业三维扫描数字化农业3d打印制造应用-CASAIM中科广电
  • Jenkins的定时任务配置
  • THINKPHP 微联云投票系统源码独立版 + 支持刷礼物
  • Mongodb两种启动方法
  • Python:列表的浅拷贝与深拷贝
  • OnePlus Open可折叠手机:规格、价格、发布日期等详细信息汇总!
  • SQL 数据库
  • 【算法系列篇】滑动窗口
  • 多维时序 | MATLAB实现BiTCN-BiGRU-Attention多变量时间序列预测
  • Docker容器与虚拟化技术:Docker compose部署LNMP
  • 高性能服务器Nodejs操作Mysql数据库
  • ffmpeg将rtsp流转成mp4
  • 第十四天|层序遍历、226.翻转二叉树 (优先掌握递归)、101. 对称二叉树 (优先掌握递归)
  • 如何使用装rancher安装k8s集群(k8s集群图形化管理工具)
  • 类加载器与双亲委派