如何对多参数函数应用函数组合或管道?post与comment关联实操
解决方案
核心思路是利用柯里化+部分应用将双参数逻辑拆分为两个一元处理流程:先将评论数组预处理为按postId索引的查找字典,再将该字典作为固定参数传入处理文章数组的管道,全程符合函数式纯函数、一元参数适配的要求。
完整实现代码如下:
import axios from 'axios' import * as R from 'ramda' // 预处理评论为 【postId -> 评论内容数组】的查找字典 const buildCommentDict = R.pipe( R.groupBy(R.prop('postId')), R.map(R.pipe( R.pluck('body'), R.uniq // 保留原代码的去重逻辑,不需要可直接删除 )) ) // 柯里化函数:接收评论字典、文章数组,返回合并后的完整对象数组 const mergePostsWithComments = R.curry((commentDict, posts) => R.pipe( R.map(post => R.assoc( 'comments', R.propOr([], R.prop('id', post), commentDict), post )) )(posts) ) // 主执行逻辑 const getMergedPostData = async () => { // 并行请求两个接口提升性能 const [postRes, commentRes] = await Promise.all([ axios.get('https://jsonplaceholder.typicode.com/posts'), axios.get('https://jsonplaceholder.typicode.com/comments') ]) const commentDict = buildCommentDict(commentRes.data) // 部分应用传入评论字典,得到仅接收posts数组的一元函数,适配管道调用要求 const mergeWithCurrentComments = mergePostsWithComments(commentDict) return mergeWithCurrentComments(postRes.data) } // 调用测试 getMergedPostData().then(console.log)
关键说明
- 双输入适配:通过
R.curry将双参数的合并函数转为可分步传参的柯里化函数,提前传入预处理好的评论字典后,得到的就是符合管道要求的一元函数,完全适配函数式的组合/管道能力 - 性能优化:提前将评论转为O(1)查找的字典,避免两层循环匹配,时间复杂度从O(m*n)降到O(m + n)
- 灵活调整:如果需要保留完整评论对象而非仅提取body字段,删除
R.pluck('body')这一行即可
内容的提问来源于stack exchange,提问作者Ahmed Osama
相关产品推荐
相关产品推荐

