by Rodeoclash · 4y ago · 0 comments
One of the best tools I found to really dive into functional programming in JavaScript was Lodash's "fp" variant. It will swap the order of the arguments to its functions and curry them all by default. So you're building a function to "add one"
const addOne = map(function(n) { return n + 1 });
Can then be applied against an array of numbers: addOne([1, 2 ,3])
> [2, 3, 4]
This is fairly basic though. Where it really shines is when you start to use the `flow` function will can be used to compose multiple functions together (and makes the order of execution follow from left to right) flow(addOne, reverse)([1, 2, 3])
> [4, 3, 2]
I find this is one of the small redeeming features of JavaScript! addOne :: [Int] -> [Int]
It's not idiomatic in FP (as far as I'm aware) to bake the structure in like that. const addOne = (n) => { return n + 1}
map(addOne)([1, 2, 3])
> [2, 3, 4]
Would decompose the addOne into its own standalone function.My only excuse was that I was in a hurry due to Minecraft time with my son.
pipe(
xs,
reverse,
A.map(addOne),
)Theres also Ramda (https://ramdajs.com/), which I slightly prefer because the documentation is significantly better.
That said, if I was on a project with a bunch of developers that really grok'd FP concepts then Rambda would be my first pick, absolutely.
A note from personal experience: never mix fp and normal variants of date-fns and lodash in one project. If you import isAfter from date-fns/fp in one file and date-fns in another (or your editor imports it for your) you‘re gonna have a BAD time.