Search code examples
functional-programmingcompositionramda.js

How to use Ramda compose with more than two functions?


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?


Solution

  • 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.