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();
相关推荐
weixin-a153003083163 分钟前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
ai小鬼头30 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
wen's37 分钟前
React Native 0.79.4 中 [RCTView setColor:] 崩溃问题完整解决方案
javascript·react native·react.js
黄雪超1 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice1 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变1 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
vvilkim1 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim1 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron
lijingguang1 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#