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();
相关推荐
LetsonH5 分钟前
Python工具链UV整合环境管理
开发语言·python·uv
Yvonne爱编码14 分钟前
CSS- 1.1 css选择器
前端·css·状态模式·html5·hbuilder
SHIPKING39315 分钟前
【HTML】个人博客页面
javascript·css·html
山河故人16325 分钟前
uniapp使用npm下载
前端·npm·uni-app
zm37 分钟前
UDP 多点通信
开发语言·php
-曾牛1 小时前
基于微信小程序的在线聊天功能实现:WebSocket通信实战
前端·后端·websocket·网络协议·微信小程序·小程序·notepad++
.小墨迹1 小时前
Apollo学习——planning模块(3)之planning_base
linux·开发语言·c++·学习·自动驾驶
小喵喵生气气1 小时前
Python60日基础学习打卡D26
开发语言·python
一口一个橘子1 小时前
[ctfshow web入门] web72
前端·web安全·网络安全
Web极客码1 小时前
如何使用WordPress SEO检查器进行实时内容分析
前端·seo·wordpress