Why Be Functional?
1 | // Plain JS |
- Self-document
- Testable
- Short
- Compositional
Basis
Meeting Particial Apply & Curry
Particial Apply - Specifies some arguments up front, producing a function that’s waiting for all the rest arguments.
1 | let greet = (salutation, title, firstName, lastName) => |
Curry - Call a function with incomplete arguments, it returns a function which takes the remaning arguments
1 | let add = (x, y) => x + y; |
But what if I have lots of parameters?
1 | let crazyFun = (a, b, c, d, e) => ...; |
We can do:
1 | crazyFun(1, 2, 3, 4, 5); |
###Function Factory - Compose
Compose - The reverse of pipe
1 | let toUpperCase = function(x) { |
You can implement a compose
by many ways:
1 | function composeTwo(f, g) { |
Pure Function
Pure function - A function that, given the same input, will always return the same output and does not have any observable side effect.
Think about slice
and splice
: the latter change the origin array, it’s impure.
1 | var xs = [1, 2, 3, 4, 5]; |
Side effects may include, but are not limited to
- changing the file system
- inserting a record into a database
- making an http call
- mutations
- printing to the screen / logging
- obtaining user input
- querying the DOM
- accessing system state - free variables, etc.
A pure function can’t produce any observable effect.
Immutability
- Don’t ever make a change to value.
- Always create a new copy.
- Helpful for reducing side effects.
We can use lenses to “make change”:
1 | let xLens = R.lens(R.prop('x'), R.assoc('x')); |