Last active
January 26, 2021 17:57
-
-
Save abrahamjuliot/d89dcc54992326c0e6aa30a597974337 to your computer and use it in GitHub Desktop.
Functional Programming 101
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
//Immutable state: | |
const state = Object.freeze({ }) | |
//Pure functions: | |
const fn = (val, dependencies = [ ]) => val+1 | |
//Higher-order functions: | |
const decorate = (x, fn) => { | |
return fn(x) | |
} | |
const make = (x) => { | |
return (y) => x+y | |
} | |
//Currying: | |
const make = (x) => { | |
return (y) => x+y | |
} | |
make(1)(2) //=> 3 | |
const executeLater = make(5) | |
executeLater(6) //=> 11 | |
//Factories: | |
const do = (options) => { | |
const private = options | |
return { } | |
} | |
//Recursion: | |
'use strict' | |
const do = (x) => i < 3 && do(x++) | |
do(0) | |
//Object composition: | |
const doesSomething = (state) => { | |
return { } // has-a, uses-a, can-do | |
} | |
const do = () => { | |
const state { } | |
return Object.assign( | |
{ }, | |
doesSomething(state) | |
) | |
} | |
//Function composition: | |
const accumulator = (val, fn) => fn(val) | |
const pipe = (...fns) => value => fns.reduce(accumulator, value) | |
const compose = (...fns) => value => fns.reduceRight(accumulator, value) | |
const lower = s => s.toLowerCase() | |
const reverse = s => s.split('').reverse().join('') | |
const question = s => s + '?' | |
const piped = pipe(lower, reverse, question) | |
piped('cat') //=> tac? | |
const composed = compose(lower, reverse, question) | |
composed('cat') //=> ?tac | |
//Class (Prototype Delagate) using factories instead of new keyword & constructor: | |
// Class Person | |
const Person = ({name, type = 'robot'}) => { | |
const age = 27 // private | |
return Object.freeze({ // immutable | |
type, | |
describe () { | |
return `${name}, a ${this.type}, is a ${this.mood} ${age} year old.` | |
}, | |
getName() { return name }, | |
getAge() { return age } | |
}) | |
} | |
// Worker extends Person() | |
const Worker = (props) => { | |
return Object.assign( | |
Object.create(Person(props)), { | |
mood: 'happy', | |
/*type: 'frog'*/ //=> No no :/ | |
}) | |
} | |
// Dude is a new Worker | |
const Dude = Worker({name: 'Joe'}) | |
Dude.describe() //=> 'Joe, a robot, is a happy 27 year old.' :) | |
/*Dude.type = 'bird'*/ //=> No no :/ | |
/*Dude.age */ //=> undefined :O |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment