Perform a calculation where two numbers are multiplied together and the result is added to a third number

I'm just getting started with functional programming and I'm attempting to create a function that multiplies two numbers together and then adds the result to a third number using TypeScript with rambda.

My goal is to have a function that takes three numbers, performs the operation as follows: f(a, b, c) = a + (b * c). Here's what I've accomplished so far:

Using Imperative style

const f = (a: number, b: number, c: number) => a + b * c;

Using Functional style

const add = (a: number) => (b: number) => a + b;
const mul = (a: number) => (b: number) => a * b;
const f = (a: number, b: number, c: number) => add(a)(mul(b)(c));

The issue with the above solution is that the function f lacks readability, which is why I am trying to achieve the same outcome with Rambda. My desired approach would be something like const f = R.pipe(mul, add);, but I'm unsure how to define the functions add and mul to make that work.

Here is my attempt:

const add = (a: number) => (b: number) => a + b;
const mul = (a: number) => (b: number) => a * b;
const f = R.pipe(mul, add);

However, this results in an error:

Argument of type '(a: number) => (b: number) => number' is not assignable to parameter of type '(a: number) => number'.
  Type '(b: number) => number' is not assignable to type 'number'.

Answer №1

prioritize readability

Function composition shines when used with unary functions. While it's not impossible to compose binary or ternary functions, it may end up being more trouble than it's worth.

const f = (a, b, c) =>
  add(a, mul(b, c))

That's all there is to it! The code remains clear and easy to understand.

"but mom, I want pipe"

If you really want to use compose (or pipe), you can simplify by partially applying add and mul -

const g = a => b =>
  compose(add(a), mul(b))

For further insight: Exploring the concepts of curry and function composition in JavaScript

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

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

What are some ways I can enhance the typography within Material UI?

Currently, I am in the process of developing a custom theme utilizing createMuiTheme. However, my application requires more typography variants than what Material UI provides out of the box. I need to extend the typography so that it aligns with my specifi ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

Is there a faster way to create a typescript constructor that uses named parameters?

import { Model } from "../../../lib/db/Model"; export enum EUserRole { admin, teacher, user, } export class UserModel extends Model { name: string; phoneNo: number; role: EUserRole; createdAt: Date; constructor({ name, p ...

What is the best way to repurpose a variable in Angular's TypeScript?

I'm currently working on an application that utilizes the following technologies. In my Typescript file named "test.page.ts", there is a variable called "response: any" that I need to reuse in another Typescript file named "test2.page.html" by calling ...

Create a Typescript function that adheres to a specified type

Imagine a scenario where a specific type of function is declared within a type type Callback = (err: Error | null, result: any) type UselessFunction = (event: string, context: any, callback: Callback) => void The objective is to declare functions that ...

In React Router, redirect when location.state is not defined

import React, { useState } from "react"; import { Redirect } from "react-router-dom"; function Update(data) { if(!data.location.state) return <Redirect to="/"/> const [name, setName] = useState(dat ...

The TS2345 error is triggered when using the fs.readFile function with specified string and

Attempting to utilize the fs.readFile method in TypeScript, my code looks like this... import {readFile} from 'fs'; let str = await readFile('my.file', 'utf8'); This results in the following error message: TS2345: Argumen ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

Struggling to create a functioning toggle button using jQuery in a React application

I've encountered an issue with my react web application. I'm trying to implement a voting system where clicking the like button changes its color and functionality, allowing it to be liked only once. If clicked again, it should return to a neutra ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

I possess both a minimum and maximum number; how can I effectively create an array containing n random numbers within

Given a minimum number of 10.5 and a maximum number of 29.75, the task is to generate an array within these two ranges with a specific length denoted by 'n'. While the function for generating the array is provided below, it is important to calcul ...

Using the function goToPage() within the TabbedHeaderPager component

I am currently working on a project that involves using TabbedHeaderPager, and I need to change tabs programmatically. I have been attempting to use the function goToPage() but have run into difficulties accessing it. I have tried passing it as a prop an ...

Displaying related objects information from a single object in AngularFire2 can be achieved by following these steps

As a newcomer to Angular and Firebase, I apologize if my question seems basic. I'm seeking guidance on how to display related object information from one object in angularfire2. Specifically, I want to show the role names assigned to a user. Here is ...

The current Angular 11 build seems to lack in producing sufficient Lazy chunk files

Currently, I am working on implementing lazy loading for modules from different libraries in my project. This involves utilizing two libraries located in the node_modules directory, which are then lazily loaded by the main application. Below is a snippet o ...

Why is TS1005 triggered for Redux Action Interface with an expectation of '=>'?

I'm finding it difficult to identify what's causing this issue, as shown in the esLint error from Typescript displayed in the screenshot below: https://i.stack.imgur.com/pPZa7.png Below is the complete code, which consists of actions for redux. ...

My reselect function seems to be malfunctioning - I'm not receiving any output. Can anyone help me

I'm looking to implement reselect in my code to retrieve the shopping cart based on product ids. Here's my reselect.ts file: import { createSelector } from "reselect"; import { RootState } from "../store"; export const shopp ...

Is it feasible to stop closure from capturing external variables in TypeScript?

Imagine I have the following piece of Typescript code: const a = 456 const b = () => a Is there a way to make the Typescript compiler detect and flag an error or warning during compilation indicating that function b is accessing an external variable a ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

Enhancing the efficiency of a TypeScript-written file content parsing class

Seeking advice on optimizing a typescript module used by a VSCode extension. This module accepts a directory and parses the content within the files, which can be time-consuming for directories with a large number of files. To avoid copying the entire cla ...