How to use Ramda compose with more than two functions?

541 views Asked by At

It's my first time trying out functional programming with Ramda. I am trying to build an api endpoint string by composing multiple functions.

This works:

const endpoint = str => str && str.toUpperCase() || 'default'
const protocol = str => `https://${str}`
let finalEndpoint = R.compose(protocol, endpoint)

var result = finalEndpoint('api.content.io')

result is now https://API.CONTENT.IO as expected

But now I want to add more functions to this pipeline:

const params = val => `?sort=desc&part=true`
const query = val => `query={ some: value, another: value}`

But when I try to compose everything together like this:

let finalEndpoint = R.compose(protocol, endpoint, params, query)
var result = finalEndpoint('api.content.io')

I just get https://?SORT=DESC&PART=TRUE whereas I wanted

https://API.CONTENT.IO??sort=desc&part=true&query={ some: value, another: value}

What combination of chaining and composition do I use to get the above result?

2

There are 2 answers

2
Scott Sauyet On BEST ANSWER

A variation of this that might seem familiar to Ramda users would be to write this in a pipeline of anonymous functions:

const finalEndpoint = pipe(
  or(__, 'default'),
  concat('https://'),
  concat(__, '?sort=desc&part=true&'),
  concat(__, 'query={ some: value, another: value}')
)

finalEndpoint('api.content.io'); 
//=> https://api.content.io?sort=desc&part=true&query={ some: value, another: value}

Such a points-free version might or might not be to your taste, but it's an interesting alternative.

0
Amit Erandole On
var R = require('ramda');

const endpoint = str => `${str}` || 'default'
const protocol = str => `https://${str}`
const params = str => `${str}?sort=desc&part=true&`
const query = str => `${str}query={ some: value, another: value}`

let finalEndpoint = R.compose(query, params, protocol, endpoint)

var result = finalEndpoint('api.content.io')

console.log(result)

Turns out I wasn't using the str parameter correctly