onion洋葱模型

javascript 复制代码
const log = console.log;
function m1(next) { log(1); next(); log(2); }
function m2(next) { log(3); next(); log(4); }
function m3(next) { log(5); next(); log(6); }

function end() { log('end'); }
function m3_end() { m3(end); }
function m2_end() { m2(m3_end); }
m1(m2_end);
// 打印顺序 1 3 5 end 6 4 2

利用高阶函数

fn => compose();

高阶函数:

  1. 入口参数是函数;
  2. 返回函数;
  3. 两者皆备;
javascript 复制代码
const log = console.log;
function m1(next) { log(1); next(); log(2); }
function m2(next) { log(3); next(); log(4); }
function m3(next) { log(5); next(); log(6); }

let ms = [];
use(m1); use(m2); use(m3);
function use(mx) {
  ms.push(mx);
}

let index = 0;
function compose(index = 0) {
  if (index === ms.length) {
    return () => { log('end') };
  }
  return () => {
    ms[index](compose(index + 1));
  };
}

let fn = compose();
fn();
相关推荐
weixin199701080162 分钟前
《识货商品详情页前端性能优化实战》
前端·性能优化
Forever7_2 分钟前
重磅!Vue3 手势工具正式发布!免费使用!
前端·前端框架·前端工程化
用户806138166593 分钟前
发布为一个 npm 包
前端·javascript
smchaopiao16 分钟前
Python中字典与列表合并的问题与解决方法
开发语言·python
敲代码的瓦龙33 分钟前
Java?面向对象三大特性!!!
java·开发语言
树上有只程序猿34 分钟前
低代码何时能出个“秦始皇”一统天下?我是真学不动啦!
前端·后端·低代码
TT_哲哲34 分钟前
小程序双模式(文件 / 照片)上传组件封装与解析
前端·javascript
2501_9216494935 分钟前
期货 Tick 级数据与基金净值历史数据 API 接口详解
开发语言·后端·python·websocket·金融·区块链
野犬寒鸦39 分钟前
Redis复习记录day1
服务器·开发语言·数据库·redis·缓存