Last active
December 28, 2016 16:57
-
-
Save nonlogos/b7929cd9a09ab6015aaa1e30a2ca3f8e to your computer and use it in GitHub Desktop.
Functional Programming Concepts and Examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pure Functions | |
// Programming without side-effects | |
Remove: | |
1. Assignments | |
2. Loops (use recursion instead) | |
3. Freeze all array literals and object literals (remove Date and Math.random) | |
// MONAD | |
1. is an object | |
2. constructor is a monad because it's a function that returns a monad | |
// Functional Programming Patterns | |
// src: https://medium.com/@chetcorcos/functional-programming-for-javascript-people-1915d8775504#.y9ecpc487 | |
// src: http://fr.umio.us/why-ramda/ | |
// Compose Functions - second function is evaluated first | |
const add1 = a => a+1 | |
const times2 = a => a *2 | |
const compose = (a, b) => c => a(b(c)) | |
const add1OfTimes2 = compose(add1, times2) | |
// console.log(add1OfTimes2(5)) | |
// Pipe (piping an array of functions) | |
const pipe = fns => x => fns.reduce((v, f) => f(v), x) | |
const times2Add1 = pipe([times2, add1]) | |
// console.log(times2Add1(5)) | |
// Pipe example 2 | |
const formalGreeting = name => `Hello ${name}` | |
const casualGreeting = name => `sub ${name}` | |
const male = name => `Mr. ${name}` | |
const female = name => `Mrs. ${name}` | |
const doctor = name => `Dr. ${name}` | |
const phd = name => `${name} PhD` | |
const md = name => `${name} M.D.` | |
// ext 1 | |
// console.log(formalGreeting(male(phd("Chet")))) | |
// ext 2 | |
const identity = x => x | |
const greet = (name, options) => { | |
return pipe([ | |
//greeting | |
options.formal ? formalGreeting : casualGreeting, | |
//prefix | |
options.doctor ? doctor : | |
options.male ? male : | |
options.female ? female : | |
identity, | |
//suffix | |
options.phd ? phd : | |
options.md ? md : | |
identity | |
])(name) | |
} | |
// console.log(greet('Chet', {formal: true, male: true, phd: true})) | |
// Function currying | |
const users = [{name: 'chet', age:25}, {name:'joe', age:24}] | |
R.pipe( | |
R.sortBy(R.prop('age')), // sort user by the age property | |
R.map(R.prop('name')), // get each name property | |
R.join(', '), // join the names with a comma | |
)(users) | |
// => "joe, chet" | |
// monad | |
list = [-1,0,1] | |
list.map(inc) // => [0,1,2] | |
list.map(isZero) // => [false, true, false] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment