柯里化、组合、管道

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 柯里化是把一个多参数函数转化成一个嵌套的一元函数的过程
function currying (fn) {
  let _args = [], max = fn.length
  let closure = function (...args) {
    // 先把参数加进去
    _args.push(...args)
    // 如果参数没满,返回闭包等待下一次调用
    if (_args.length < max) return closure
    // 传递完成,执行
    return fn(..._args)
  }
  return closure
}
function add (x, y, z) {
  return x + y + z
}
 
var curryAdd = currying(add)
// curryAdd(1, 2)(3) // 6
console.log(curryAdd(1, 2)(3))
 
 
function afn (a) {
  return a * 2;
}
function bfn (b) {
  return b * 3;
}
 
// 将多个函数组合成一个函数
// 管道 执行顺序是从左到右执行的
const pipe = (...fns) =>
  val => {
    return fns.reduce((acc, fn) => {
      return fn(acc)
    }, val);
  }
let pipeFn = pipe(afn, bfn);
console.log(pipeFn(4)); // 24
 
// 组合 执行顺序是从右到左执行的
const compose = (...fns) => val => {
  return fns.reverse().reduce((acc, fn) => { return fn(acc) }, val)
};
let myfn = compose(afn, bfn);
console.log(myfn(4)); // 24

  

posted on   sss大辉  阅读(22)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
历史上的今天:
2021-03-29 webpack编写自定义Loader
2021-03-29 react 条件渲染、列表渲染
2021-03-29 css三列布局(两边固定中间自适应)
2021-03-29 css垂直水平居中
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示