During a recent interview, I was tasked with retrieving data from the jsonplaceholder
/posts and /comments endpoints and creating a function to match comments with posts where comment.postId == post.id
, then constructing a unified JSON object containing each post along with its corresponding comments.
I've been attempting to tackle this in a functional programming style, but I'm struggling to handle two arrays (two inputs) within pipelines, compositions, or transducers as they typically accept unary functions.
I even considered using two separate pipelines - one for processing the comments and another for posts - and combining their workflows at the end, but I hit roadblocks during implementation.
The best solution I could devise so far involves mapping the comments themselves into an array of objects, where each object includes a postId
representing the post, and a comments
property that contains an 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))
If anyone has any insights on how to approach this problem in a more functional manner, I would greatly appreciate it.