What are the steps for implementing function composition or pipelines with a multi-parameter function?

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.

Answer №1

It seems like there may be a misunderstanding in the original question. While the function being discussed is quite straightforward, here is how I would approach it:

const organizeData = ([users, posts]) => 
  users .map (u => ({
    ...u,
    posts: posts .filter (p => p.userId == u.id)
  }))

const fullInfo = (userUrl, postUrl) => 
  Promise .all ([axios .get (userUrl), axios .get (postUrl)]) 
    .then (organizeData)

fullInfo (
  'https://jsonplaceholder.typicode.com/users',
  'https://jsonplaceholder.typicode.com/posts'
) .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>

As one of the creators of Ramda, I am very passionate about functional programming, but in this particular scenario, I'm not sure if it adds much value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identify all tables using jQuery with an ID that begins with

Is there a way to use jQuery to select tables with IDs that start with a specific sentence? For example: <table id="Tab_01"> <tr> <td>.... <tr> .... </table> <table id="Tab_02"> ...

Creating a span element to replace the list item class in a JavaScript Modal Pop-up

I recently set up a portfolio website that showcases my projects. When you click on a project, a modal window opens with a carousel gallery inside. On my .html page, the projects are organized like this: <li class="Project" data-modal="myModal_1"> ...

Bizarre Object notation with JavaScript

While browsing through a Library called WebApp.net, I stumbled upon this interesting piece of code: var $h = { get HEAD() { return 0 }, get BACK() { return 1 }, get HOME() { return 2 }, get LEFT() { return 3 }, get RIGHT() { return 4 } ...

Using NodeJS to assign key-value pairs to a JSON object

I am currently working with a NodeJS script that receives data in the form of "key, value" pairs and I need to transform this data into a JSON object. The data is obtained using SNMP where the key corresponds to the OID. My goal is to efficiently map thes ...

The Angular reactive form is being submitted without completing the submission process

I've been working on an Angular 5 reactive form and everything seems to be functioning correctly. However, I've encountered a strange issue with a button used to close the form by hiding it from view. Whenever I click on this close button, the f ...

How to Implement Infinite Scrolling in Ionic Framework Using HTTP Requests

Recently, I started using the amazing ionic framework and I am new to angular. I have a web service up and running, and my app is supposed to load data. I have succeeded in retrieving data, however, the WordPress rest API sends data in the form of pages. I ...

What steps should I take to fix the following error: TypeError: undefined is not an object when trying to evaluate '_bip.default.generateMnemonic'?

I'm in the process of developing a mobile application and I find myself in need of utilizing bip39 for passphrase generation. However, after installing the necessary package, I encountered errors related to missing packages like stream buffer events. ...

"Encountering a Three.js issue when attempting to incorporate over 37 spotlights in the scene

My project involves utilizing Three.js r58 (with the WebGLRenderer) to display a 3D model of a building with detailed information about the positions and dim levels of the lights inside. For each light sourced from the database, I create a CubeGeometry ob ...

Module 'angular2/angular2' not found

Currently, I am working on a node application with angular2 and gulp. One of the components I have created is login.ts: import {Component, View} from 'angular2/angular2'; import {FormBuilder, formDirectives } from 'angular2/forms'; @C ...

What is the method for inserting JSON data into a select element's options?

Below is the HTML code snippet provided: <html> <head> <link rel="stylesheet" type="text/css" href="CarInfoStyle.css"> </head> <script src="CarInfoJavascript.js"></script> <body> <div class="search ...

In the realm of Angular and TypeScript, one may encounter an error stating that '"void' cannot be assigned to a parameter of type '(value: Object) => void"

I’m facing difficulties in resolving this issue. I created a web API using .NET, and now I’m attempting to call this API in an Angular project. //movie.ts export class Movie{ ID: number; Title: number; GenreId: number; Duration: number ...

Steps for converting JSON into a structured indexed array

My goal is to efficiently convert the data retrieved from my firebase database into a format suitable for use with a SectionList. I have successfully established a part of the data structure, but I am facing challenges in associating the data correctly. ...

Enhancing user experience with VideoJS player overlay buttons on mobile devices

I am currently using VideoJs player version 4.2. When I launch a videojs player on Safari browser in an iOS device, it defaults to native controls. However, when I pause the player, overlay buttons (links to navigate to other pages) are displayed on the v ...

Utilizing Axios for communication between backend and frontend

My development setup includes reactjs for the frontend and mongoDB for the backend database. Below is the backend react code: const express = require("express"); const jwt = require("jsonwebtoken"); const bcrypt = require("bcrypt"); const { User, Verifica ...

arranging data in various categories with React.js

Can anyone figure out why this code is struggling to properly sort based on columns? sort(key){ this.setState({ [`toggle-${key}`]: !this.state[`toggle-${key}`], data: sortBy(this.state.data, [key], this.state[`toggle-${key}`]).map(v => ...

Leveraging the power of both TypeScript 2.3 and 2.4 concurrently within Visual Studio 2015.3 on a single machine

Can TS 2.3 and TS 2.4 be used on the same machine simultaneously? For example, I have one project in VS 2015.3 compiling with TS 2.3 and another project compiling with the latest TypeScript version (TS 2.4). I recently installed TypeScript 2.4, which aut ...

Use Typescript in combination with React/Redux to showcase a dynamic table on the

Looking to create a React TypeScript Redux application that showcases a table using an API endpoint provided at https://example.com/users The goal is to construct a table with 4 columns: Name, Email, City, and Company, utilizing the API response to popula ...

Upon returning to the previous page, the checkbox remains checked and cannot be unchecked

Here is the code I'm using to append checkbox values with a hash in the URL. However, when navigating back, the checkboxes remain checked. Take a look at the code snippet below: <html> <head> <script src="http://ajax.googleapis.com/aja ...

Next.js Head component will not repeat the same Meta Tags

In my Next.js project, I have implemented different meta tags with various media targets in the Head section: <Head> <meta name="theme-color" media="(prefers-color-scheme: light)" content="#7f8fa6"/> <meta name= ...

What is the best way to reset a looping variable in a Node.js application?

I have encountered an issue with an API method in my nodejs app. Within one of my controllers, I am attempting to generate pages upon clicking. However, I have found that when calling the method, my for loop fails to reset the values to their default state ...