FP with Ramda

Content

  • FP: Practical Explanation
  • Ramda: What is it about?
  • Code Examples

Functional Programming

  • (almost) everything is a function
  • functions are (almost) always pure
  • immutable state (== no object manipulation)

Difference to OOP:

o.f() vs. f(o)

Ramda

enables FP with JS

What is it?

  • Utility Library (comparable to Lodash, Underscore)
  • pure functions, immutable state

 

AND:

  • Every function is curried by default
  • data to operate on comes last

CurrYING

apply parameters of a function in several calls

Goal: have unary functions

// A normal function with two arguments
const myFunction = (param1, param2) => { console.log(`I got called with ${param1} ${param2}` };
myFunction('Hello', 'World') // I got called with Hello World
// Now lets curry it
import {curry} from 'ramda';
const myCurriedFunction = curry(myFunction);

// does NOT execute the function, but stores the first arugment
const myCurriedHelloFunction = myCurriedFunction('Hello'); 
// ... do other things and then later
myCurriedHellFunction('World') // now prints 'I got called with Hello World');

Operated data comes last

_.forEach([1,2,3], (val) => console.log(val));
ramda.forEach((val) =>  console.log(val), [1,2,3]);

FUNCTION COMPOSITION

the big Goal

example time

Use case

The price for all selected products should be calculated and displayed as followed:

  • take all price relevant products. Price relevant means: they are selected, are in stock and have type "sellable"
  • sum up the the prices of all those products
  • if sum is 0, return nothing, if 1, append "Dollar", else append "Dollars"

Good Parts:

  • precise & readable code
  • high reusability factor
  • small logic pieces
  • no need to write too much own code

Bad Parts:

  • Takes a while to get the "thinking"
  • Sometimes hard to make it work they way you want
  • Typings with typescript can be painful

SUMMARY

Made with Slides.com