I have this code that is building a url endpoint taking in different parameters:
const query = (obj) => {
let starter = 'query='
let queryToString = JSON.stringify(obj)
return `${starter}${queryToString}`
}
const params = (str) => `${str}`
const endpoint = (protocol, base, params, query) => {
if (!params && !query) return `${base}`
if (!params) return `${base}${query}`
return `${protocol}${base}?${params}&${query}`
}
const baseUrl = 'api.content.io'
const protocol = (secure = true) => secure ? 'https://' : 'http://'
let result = endpoint(protocol(), baseUrl, params('limit=5&order=desc'),
query({
field: 'title',
include: 'brands'
}));
console.log(result)
This builds a string like:
https: //api.content.io?limit=5&order=desc&query={"field":"title","include":"brands"}
Is it possible to refactor this code such that the conditionals inside the endpoint function can be removed, the right concatenation strings be applied and the whole thing chained into a functional call like
Endpoint.chain(protocol(p)).chain(base(b)).chain(params(p)).chain(query(q)).build()
How do I get started with doing this?
UPDATE: The solutions below are pretty good but I would like to understand how functional programmers use ADTs (Algebraic Data Types) with Monads to solve this problem. The idea is to run a chain of functions and then a fold to get back the value I want
Are you looking for something like this?
Chaining basically happens when you return the complete object in every function call. Here each function sets the value of its given chunk and returns the this object for whatever context it's attached to. Each function would be able to process the value it receives and the value function would build the url based on the set parameters.