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();
相关推荐
charlie11451419112 分钟前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
Rrvive15 分钟前
localhost 和 127.0.0.1 的核心区别
前端
蓝倾16 分钟前
如何使用Python通过API接口批量抓取小红书笔记评论?
前端·后端·api
極光未晚17 分钟前
JavaScript BOM 对象:浏览器的隐形控制塔
前端·javascript·源码
天涯学馆19 分钟前
网站秒变 App!手把手教你搞定 PWA
前端·javascript·面试
神仙别闹20 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
uu_code00723 分钟前
Android接入Pixelfree美颜SDK技术指南
前端
小鱼小鱼干23 分钟前
使用 ESLint 实现 Git Commit 前的语法检查
前端
用户92724725021924 分钟前
PHP + CSS + JS 数据采集与展示系统
javascript
码哥DFS39 分钟前
Flex布局原理
前端·css·css3