[英]How to apply functions composition or pipelines on multi-parameter function?
在一次采访中,我被要求点击jsonplaceholder
/posts 和 /comments 端点并编写一个 function 以返回与其中comment.postId == post.id
的帖子匹配的评论,然后组成一个完整的 JSON ZA8CFDE68331BD59EB26ACZ,其中包含 6 个评论它。
我一直在尝试以功能方法实现它,但找不到处理 2 arrays(2 个输入)作为管道、组合、转换器都接受一元函数的方法。
我什至想过有两个管道,一个用于处理评论,另一个用于帖子,最后加入他们的工作流程,但无法实现。
我能想到的只是将评论本身映射为一个对象数组,其中postId
作为一个数字,表示每个帖子, comments
作为字符串数组
import axios from 'axios'
import _ from 'ramda'
const { data: comments } = await axios.get(
'http://jsonplaceholder.typicode.com/comments',
)
const cIds = (comments) =>
_.pipe(
_.groupBy(_.prop('postId')),
_.map(_.pluck('body')),
_.map(_.flatten),
_.map(_.uniq),
_.toPairs,
_.map(_.zipObj(['postId', 'comments'])),
)(comments)
console.log(cIds(comments))
所以有人知道如何以功能性的方式做到这一点吗?
我想我在问题中遗漏了一些东西。 这听起来像是一个相当简单的 function。 我可能会这样写:
const consolidate = ([posts, comments]) => posts.map (p => ({...p, comments: comments.filter (c => c.postId == p.id) })) const fullPosts = (postUrl, commentUrl) => Promise.all ([axios.get (postUrl), axios.get (commentUrl)]).then (consolidate) fullPosts ( 'https://jsonplaceholder.typicode.com/posts', 'https://jsonplaceholder.typicode.com/comments' ).then (console.log, console.warn)
.as-console-wrapper {max-height: 100%;important: top: 0}
<script>const axios = {get: (url) => fetch (url).then (r => r.json ())} // dummy axios</script>
我是 Ramda 的创始人之一,也是我的忠实粉丝,但我不知道它在这里提供了什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.