Ramda.js in Real World Productions
— A series about using Ramda.js in real world productions. This is the first article of the series.
We have to generate options for `month` field and `year` field.
For `month` field, there should be 01, 02, 03, 04, …, 11, 12. Notice that 1 ~ 9 should be formatted as 01, 02, …, 09.
For `year` field, options should start from the current year, to the next 10 years. And they should be converted from 4 digit to 2 digit.
When user submits, we should concat two strings.
First Attempt
Let’s get started from generating options of months.
I was reminded of Lodash’s `times` function. Luckily, Ramda has its own `times` function as well.
(Number → a) → Number → [a]
Calls an input function
n
times, returning an array containing the results of those function calls.
fn
is passed one argument: The current value ofn
, which begins at0
and is gradually incremented ton - 1
.
Example:
R.times(R.identity, 5); //=>[0,1,2,3,4]
Great! It is definitely what we want!
R.times(R.identity, 12);
It generates [0, 1, 2, ..., 10, 11]
.
We have to add all items in the list by 1.
Then the simplest and most common example function for introduction to FP comes to rescue. It’s `add` function.
R.times(R.add(1), 12);
Now our list becomes [1, 2, 3, ..., 11, 12]
. Great.
R.pipe
We now want to covert [1, 2, 3, ..., 11, 12]
, a list of numbers, to ["01", "02", ..., "11", "12"]
, a list of strings.
Performs left-to-right function composition. The leftmost function may have any arity; the remaining functions must be unary.
In some libraries this function is named
sequence
.
So, how will we apply this function?
add(1) ==> toString ==> format
becomes
R.pipe(R.add(1), R.toString, format)
.
Write a simple format
function :
Applies this composed function to times
function:
R.times(R.pipe(R.add(1), R.toString, format), 12);
Finally, we get ["01", "02", ..., "11", "12"]
! Perfect!
For Year Field
It looks similar. It is quite simple after we have learned how to get month field options.
We can concat two selected values, and send it to backend now.
{ "pan": "...", "cvv": "123", "expiry": month.concat(year) }
Thank you for reading. I will write more about Ramda.js since it really helps and can be applied in real world productions.
I discussed Ramda.js with my colleagues.
Mr. N (obsessed with FP and Ramda): format
should have been written as:
R.ifElse(R.equals(str.length, 1), `0${str}`, str)
Me: Sometimes we should just use vanilla.js.
Mr. R: … It is a textspeak.