There are various ways to approach writing a function like this. While your focus is on learning how to utilize the pipe
function, allow me to introduce a technique that starts with functions similar to the ones you already have:
const getSQLQuery = ( { lang } ) => `My query is ${lang}`;
const getMarket = country => `my country is ${country}`;
const flipAndJoin = pipe(reverse, join(' and '))
const comp = useWith(unapply(flipAndJoin), [getMarket, getSQLQuery])
comp("Spain", {lang: "uk"}); //=> ""My query is uk and my country is Spain"
Now, let's address some questions:
- What is preventing your function from working?
- How can you rectify this issue?
- How can you ensure that
pipe
works as intended?
What is preventing your function from working?
The reason your function fails is that pipe
expects multiple functions as parameters, with at least one being mandatory. The first parameter you provide is getSQLQuery( queryParams )
, which is the output of calling getSQLQuery
with an argument. This results in a string, not a function. Hence, when you attempt to wrap it in a pipe
, it encounters an error. (The mention of 'arity' pertains to Ramda internals, where the initial function passed to pipe
determines the number of parameters for the resulting function.)
How can you rectify this issue?
I presented a solution earlier. MarioF also addresses this with minimal modifications to your original functions.
However, none of these methods are as straightforward as
const comp2 = (country, queryParams) =>
`My query is ${queryParams.lang} and my country is ${country}`
comp2("Spain", {lang: "uk"}); //=> ""My query is uk and my country is Spain"
How can you ensure that pipe
works as intended?
It is vital to understand the functionality of pipe
.
Consider a function like this:
const getUpperAddr(userName, collection) {
const configStr = getUserConfig(userName, collection);
const config = JSON.parse(configStr);
const address = prop('address')(config);
const addrLine1 = prop('addrLine1')(address);
const upperAddr = toUpper(addrLine1);
return upperAddr;
}
In essence, each successive local variable in this function is generated by applying a function to the preceding one, except for the initial variable that utilizes the function parameters. The end result is the final local variable.
pipe
simplifies this process and eliminates the necessity for all the intermediary variables (including parameter names). It achieves the same outcome through a more declarative method:
const getUpperAddr = pipe(
getUserConfig,
JSON.parse,
prop('address'),
prop('addrLine1'),
toUpper
);
This mirrors the previous format and provides identical results for the same input. By structuring your function in the initial way, transitioning to pipe
can be done systematically. Over time, this conversion becomes instinctual, allowing you to skip the primary step altogether.