• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
夕颜
博客园    首页    新随笔    联系   管理    订阅  订阅
JavaScript函数式编程之组合函数

对数组进行遍历,然后组成合适的参数传递给回调函数,过程就是一个函数pipeline

1.Reduce

JavaScript 函数式编程实践指南 - 修言 - 掘金小册

const arr = [1, 2, 3]
const initialValue = 0  
const add = (previousValue, currentValue) =>previousValue+currentValue;
//执行顺序 0 + 1 + 2 + 3
const sumArr = arr.reduce(add,0);
console.log(sumArr) //expected output: 6
执行过程:

2.map

function add1AndPush(previousValue, currentValue) {
  // previousValue 是一个数组
  previousValue.push(currentValue + 1)
  return previousValue
}
const arr = [1,2,3]
const newArray = arr.map((num)=> num+1)
const newArray1 = arr.reduce(add1AndPush,[])
console.log(newArray);//[2, 3, 4]
console.log(newArray1);//[2, 3, 4]

3.compose

执行顺序是从右往左,也就是执行顺序是:func4 => func3 => func2 => func1

compose(
    func1,
    func2,
    func3,
    func4
)(value)

 4.pipe

执行顺序是从左往右,也就是执行顺序是:func1 => func2 => func3 => func4

const funcs = [func1, func2, func3, func4];
pipe(...funcs)(value);

 

posted on 2024-11-20 14:54  夕颜~~  阅读(14)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3