简体   繁体   中英

How to apply functions composition or pipelines on multi-parameter function?

In an interview, I was asked to hit the jsonplaceholder /posts and /comments endpoints and write a function that returns matched comments with posts where comment.postId == post.id then make a whole JSON object containing the post within the comments belongs to it.

I have been trying to implement it in a functional approach but cannot find a way of dealing with 2 arrays (2 inputs) as pipelines, compositions, transducers all accept unary functions.

I Even thought of having two pipelines one for processing the comments and the other for posts and joining their workflows at the end but couldn't implement it.

All I could come up with is mapping the comments themselves to be an array of objects where it has postId as a number that represents each post and comments as array of strings

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))

So anyone has an idea of how to do so in a functional manner?

I think I'm missing something in the question. This sounds like a fairly simple function. I might write it something like this:

 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>

I'm one of the founders of Ramda, and a big fan, but I don't know that it offers much here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM