Slide 1

Slide 1 text

Jeremy Fairbank @elpapapollo / jfairbank FUNCTIONAL PROGRAMMING BASICS IN ES6

Slide 2

Slide 2 text

Software is broken. We are here to fix it. Say hello@testdouble.com

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

¯\_(ϑ)_/¯ WHAT IS FUNCTIONAL PROGRAMMING?

Slide 5

Slide 5 text

¯\_(ϑ)_/¯ WHY FUNCTIONAL PROGRAMMING?

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Domain to Range

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

Domain Range

Slide 11

Slide 11 text

CALCULUS

Slide 12

Slide 12 text

PRINCIPLES

Slide 13

Slide 13 text

PURE & DECLARATIVE PREDICTABLE

Slide 14

Slide 14 text

IMMUTABLE STATE SAFE

Slide 15

Slide 15 text

FIRST CLASS STATE TRANSPARENT

Slide 16

Slide 16 text

COMPOSABLE FIRST CLASS CLOSURES MODULAR

Slide 17

Slide 17 text

ES2015 (ES6)

Slide 18

Slide 18 text

let age = 10; age = 11; const name = 'Tucker'; name = 'Sally'; All good Syntax error

Slide 19

Slide 19 text

const add = (x, y) => { return x + y; }; const identity = x => x;

Slide 20

Slide 20 text

const add = (x, y) => { return x + y; }; const identity = x => x;

Slide 21

Slide 21 text

const add = (x, y) => { return x + y; }; const identity = x => x;

Slide 22

Slide 22 text

const add = (x, y) => { return x + y; }; const identity = x => x;

Slide 23

Slide 23 text

const add = (x, y) => { return x + y; }; const identity = x => x;

Slide 24

Slide 24 text

const add = (x, y) => { return x + y; }; const identity = x => x;

Slide 25

Slide 25 text

const array = (...elements) => { return elements; }; array(1, 2, 3); // [1, 2, 3]

Slide 26

Slide 26 text

const array = (...elements) => { return elements; }; array(1, 2, 3); // [1, 2, 3]

Slide 27

Slide 27 text

const array = (...elements) => { return elements; }; array(1, 2, 3); // [1, 2, 3]

Slide 28

Slide 28 text

const array = (...elements) => { return elements; }; array(1, 2, 3); // [1, 2, 3]

Slide 29

Slide 29 text

const log = (...args) => { console.log(...args); }; log('Hello', 'Codestock'); // Hello Codestock

Slide 30

Slide 30 text

const log = (...args) => { console.log(...args); }; log('Hello', 'Codestock'); // Hello Codestock

Slide 31

Slide 31 text

const langs = [ 'JavaScript', 'Elm', 'Haskell', ]; const [js, ...rest] = langs; js === 'JavaScript'; rest[0] === 'Elm'; rest[1] === 'Haskell';

Slide 32

Slide 32 text

const langs = [ 'JavaScript', 'Elm', 'Haskell', ]; const [js, ...rest] = langs; js === 'JavaScript'; rest[0] === 'Elm'; rest[1] === 'Haskell';

Slide 33

Slide 33 text

const langs = [ 'JavaScript', 'Elm', 'Haskell', ]; const [js, ...rest] = langs; js === 'JavaScript'; rest[0] === 'Elm'; rest[1] === 'Haskell';

Slide 34

Slide 34 text

const langs = [ 'JavaScript', 'Elm', 'Haskell', ]; const [js, ...rest] = langs; js === 'JavaScript'; rest[0] === 'Elm'; rest[1] === 'Haskell';

Slide 35

Slide 35 text

const head = ([x]) => x; head([1, 2, 3]) === 1;

Slide 36

Slide 36 text

const head = ([x]) => x; head([1, 2, 3]) === 1;

Slide 37

Slide 37 text

const head = ([x]) => x; head([1, 2, 3]) === 1;

Slide 38

Slide 38 text

const greet = (name, greeting = 'Hi') => { console.log(greeting, name); }; greet('Codestock', 'Hello'); // Hello Codestock greet('Knoxville'); // Hi Knoxville

Slide 39

Slide 39 text

const greet = (name, greeting = 'Hi') => { console.log(greeting, name); }; greet('Codestock', 'Hello'); // Hello Codestock greet('Knoxville'); // Hi Knoxville

Slide 40

Slide 40 text

const greet = (name, greeting = 'Hi') => { console.log(greeting, name); }; greet('Codestock', 'Hello'); // Hello Codestock greet('Knoxville'); // Hi Knoxville

Slide 41

Slide 41 text

const greet = (name, greeting = 'Hi') => { console.log(greeting, name); }; greet('Codestock', 'Hello'); // Hello Codestock greet('Knoxville'); // Hi Knoxville

Slide 42

Slide 42 text

Object.assign( {}, { hello: 'Knoxville' }, { hi: 'Codestock' } ); // { // hello: 'Knoxville', // hi: 'Codestock' // }

Slide 43

Slide 43 text

Object.assign( {}, { hello: 'Knoxville' }, { hi: 'Codestock' } ); // { // hello: 'Knoxville', // hi: 'Codestock' // }

Slide 44

Slide 44 text

Object.assign( {}, { hello: 'Knoxville' }, { hi: 'Codestock' } ); // { // hello: 'Knoxville', // hi: 'Codestock' // }

Slide 45

Slide 45 text

class Point { constructor(x, y) { this.x = x; this.y = y; } moveBy(dx, dy) { this.x += dx; this.y += dy; } } function Point(x, y) { this.x = x; this.y = y; } Point.prototype.moveBy = function(dx, dy) { this.x += dx; this.y += dy; };

Slide 46

Slide 46 text

PURE

Slide 47

Slide 47 text

const add = (x, y) => x + y; add(2, 3) === 5; add(2, 3) === 5; add(2, 3) === 5;

Slide 48

Slide 48 text

const add = (x, y) => x + y; add(2, 3) === 5; add(2, 3) === 5; add(2, 3) === 5; Referentially transparent

Slide 49

Slide 49 text

× let name = 'Jeremy'; const getName = () => name; const setName = (newName) => { name = newName; }; const printUpperName = () => { console.log(name.toUpperCase()); };

Slide 50

Slide 50 text

× let name = 'Jeremy'; const getName = () => name; const setName = (newName) => { name = newName; }; const printUpperName = () => { console.log(name.toUpperCase()); };

Slide 51

Slide 51 text

× let name = 'Jeremy'; const getName = () => name; const setName = (newName) => { name = newName; }; const printUpperName = () => { console.log(name.toUpperCase()); };

Slide 52

Slide 52 text

× let name = 'Jeremy'; const getName = () => name; const setName = (newName) => { name = newName; }; const printUpperName = () => { console.log(name.toUpperCase()); };

Slide 53

Slide 53 text

describe('api', () => { beforeEach(() => mockConsoleLog()); afterEach(() => restoreConsoleLog()); it('sets and prints the name', () => { printUpperName(); expect(console.log).calledWith('JEREMY'); setName('Jet'); printUpperName(); expect(console.log).calledWith('JET'); }); }); ×

Slide 54

Slide 54 text

HIDDEN STATE IS UNCERTAIN STATE

Slide 55

Slide 55 text

const upperName = (name) => name.toUpperCase(); describe('api', () => { it('returns an uppercase name', () => { expect(upperName('Jeremy')).to.equal('JEREMY'); expect(upperName('Jet')).to.equal('JET'); }); }); ✓

Slide 56

Slide 56 text

HOW TO ACHIEVE THE RESULT IMPERATIVE

Slide 57

Slide 57 text

function doubleNumbers(numbers) { const doubled = []; const l = numbers.length; for (let i = 0; i < l; i++) { doubled.push(numbers[i] * 2); } return doubled; } doubleNumbers([1, 2, 3]); // [2, 4, 6]

Slide 58

Slide 58 text

DECLARE WHAT THE DESIRED RESULT IS DECLARATIVE

Slide 59

Slide 59 text

function doubleNumbers(numbers) { return numbers.map(n => n * 2); } doubleNumbers([1, 2, 3]); // [2, 4, 6]

Slide 60

Slide 60 text

function doubleNumbers(numbers) { return numbers.map(n => n * 2); } doubleNumbers([1, 2, 3]); // [2, 4, 6]

Slide 61

Slide 61 text

1 2 3 numbers.map(n => n * 2) 2 4 6 Domain Range

Slide 62

Slide 62 text

CREATE STATE, DON’T MUTATE IT IMMUTABLE

Slide 63

Slide 63 text

const hobbies = [ 'programming', 'reading', 'music', ]; const firstTwo = hobbies.splice(0, 2); console.log(firstTwo); // ['programming', 'reading'] console.log(hobbies); // ['music']

Slide 64

Slide 64 text

const hobbies = [ 'programming', 'reading', 'music', ]; const firstTwo = hobbies.splice(0, 2); console.log(firstTwo); // ['programming', 'reading'] console.log(hobbies); // ['music'] Slight typo + mutability

Slide 65

Slide 65 text

Object.freeze Immutable.js

Slide 66

Slide 66 text

const hobbies = Object.freeze([ 'programming', 'reading', 'music', ]); const firstTwo = hobbies.splice(0, 2); // TypeError

Slide 67

Slide 67 text

const hobbies = Object.freeze([ 'programming', 'reading', 'music', ]); const firstTwo = hobbies.splice(0, 2); // TypeError

Slide 68

Slide 68 text

FREE YOUR STATE

Slide 69

Slide 69 text

class Point { constructor(x, y) { this.x = x; this.y = y; } moveBy(dx, dy) { this.x += dx; this.y += dy; } } const point = new Point(0, 0); point.moveBy(5, 5); point.moveBy(-2, 2); console.log([point.x, point.y]); // [3, 7] ×

Slide 70

Slide 70 text

const createPoint = (x, y) => Object.freeze([x, y]); const movePointBy = ([x, y], dx, dy) => { return Object.freeze([x + dx, y + dy]); }; let point = createPoint(0, 0); point = movePointBy(point, 5, 5); point = movePointBy(point, -2, 2); console.log(point); // [3, 7] ✓ (*or object-oriented without mutation)

Slide 71

Slide 71 text

const createPoint = (x, y) => Object.freeze([x, y]); const movePointBy = ([x, y], dx, dy) => { return Object.freeze([x + dx, y + dy]); }; let point = createPoint(0, 0); point = movePointBy(point, 5, 5); point = movePointBy(point, -2, 2); console.log(point); // [3, 7] ✓ (*or object-oriented without mutation)

Slide 72

Slide 72 text

const createPoint = (x, y) => Object.freeze([x, y]); const movePointBy = ([x, y], dx, dy) => { return Object.freeze([x + dx, y + dy]); }; let point = createPoint(0, 0); point = movePointBy(point, 5, 5); point = movePointBy(point, -2, 2); console.log(point); // [3, 7] ✓ (*or object-oriented without mutation)

Slide 73

Slide 73 text

const createPoint = (x, y) => Object.freeze([x, y]); const movePointBy = ([x, y], dx, dy) => { return Object.freeze([x + dx, y + dy]); }; let point = createPoint(0, 0); point = movePointBy(point, 5, 5); point = movePointBy(point, -2, 2); console.log(point); // [3, 7] ✓ (*or object-oriented without mutation)

Slide 74

Slide 74 text

PROS SAFETY FROM ACCIDENTAL MUTATION FREE UNDO/REDO LOGS — REDUX EXPLICIT FLOW OF DATA CONCURRENCY SAFETY

Slide 75

Slide 75 text

CONS VERBOSE MORE OBJECT CREATION* MORE GARBAGE COLLECTION* MORE MEMORY USAGE* *Alleviated with libs like Immutable.js

Slide 76

Slide 76 text

FIRST CLASS FUNCTIONS

Slide 77

Slide 77 text

const multiply = (x, y) => x * y; function add(x, y) { return x + y; } const addAlias = add; const evens = [1, 2, 3].map(n => n * 2);

Slide 78

Slide 78 text

const multiply = (x, y) => x * y; function add(x, y) { return x + y; } const addAlias = add; const evens = [1, 2, 3].map(n => n * 2);

Slide 79

Slide 79 text

const multiply = (x, y) => x * y; function add(x, y) { return x + y; } const addAlias = add; const evens = [1, 2, 3].map(n => n * 2);

Slide 80

Slide 80 text

const multiply = (x, y) => x * y; function add(x, y) { return x + y; } const addAlias = add; const evens = [1, 2, 3].map(n => n * 2);

Slide 81

Slide 81 text

ENCAPSULATION CLOSURES

Slide 82

Slide 82 text

const createAdder = (x) => { return (y) => x + y; }; const add3 = createAdder(3); add3(2) === 5; add3(3) === 6;

Slide 83

Slide 83 text

const createAdder = (x) => { return (y) => x + y; }; const add3 = createAdder(3); add3(2) === 5; add3(3) === 6;

Slide 84

Slide 84 text

const request = (options) => { return fetch(options.url, options) .then(resp => resp.json()); }; const usersPromise = request({ url: '/users', headers: { 'X-Custom': 'mykey' } }); const tasksPromise = request({ url: '/tasks', headers: { 'X-Custom': 'mykey' } });

Slide 85

Slide 85 text

const request = (options) => { return fetch(options.url, options) .then(resp => resp.json()); }; const usersPromise = request({ url: '/users', headers: { 'X-Custom': 'mykey' } }); const tasksPromise = request({ url: '/tasks', headers: { 'X-Custom': 'mykey' } }); Repetitive

Slide 86

Slide 86 text

const createRequester = (options) => { return (otherOptions) => { return request(Object.assign( {}, options, otherOptions )); }; }; const customRequest = createRequester({ headers: { 'X-Custom': 'mykey' } }); const usersPromise = customRequest({ url: '/users' }); const tasksPromise = customRequest({ url: '/tasks' });

Slide 87

Slide 87 text

const createRequester = (options) => { return (otherOptions) => { return request(Object.assign( {}, options, otherOptions )); }; }; const customRequest = createRequester({ headers: { 'X-Custom': 'mykey' } }); const usersPromise = customRequest({ url: '/users' }); const tasksPromise = customRequest({ url: '/tasks' });

Slide 88

Slide 88 text

FOUNDATION FOR HIGHER ORDER PATTERNS FIRST CLASS CLOSURES

Slide 89

Slide 89 text

PARTIAL APPLICATION

Slide 90

Slide 90 text

const createAdder = (x) => { return (y) => x + y; }; const createRequester = (options) => { return (otherOptions) => { return request(Object.assign( {}, options, otherOptions )); }; }; RECALL

Slide 91

Slide 91 text

const add = (x, y) => x + y; const add3 = partial(add, 3); add3(2) === 5;

Slide 92

Slide 92 text

const add = (x, y) => x + y; const add3 = partial(add, 3); add3(2) === 5;

Slide 93

Slide 93 text

const request = (defaults, options) => { options = Object.assign({}, defaults, options); return fetch(options.url, options) .then(resp => resp.json()); }; const customRequest = partial(request, { headers: { 'X-Custom': 'mykey' } }); const usersPromise = customRequest({ url: '/users' }); const tasksPromise = customRequest({ url: '/tasks' });

Slide 94

Slide 94 text

const request = (defaults, options) => { options = Object.assign({}, defaults, options); return fetch(options.url, options) .then(resp => resp.json()); }; const customRequest = partial(request, { headers: { 'X-Custom': 'mykey' } }); const usersPromise = customRequest({ url: '/users' }); const tasksPromise = customRequest({ url: '/tasks' });

Slide 95

Slide 95 text

const partialFromBind = (fn, ...args) => { return fn.bind(null, ...args); }; const partial = (fn, ...args) => { return (...otherArgs) => { return fn(...args, ...otherArgs) }; };

Slide 96

Slide 96 text

const partialFromBind = (fn, ...args) => { return fn.bind(null, ...args); }; const partial = (fn, ...args) => { return (...otherArgs) => { return fn(...args, ...otherArgs) }; };

Slide 97

Slide 97 text

const partialFromBind = (fn, ...args) => { return fn.bind(null, ...args); }; const partial = (fn, ...args) => { return (...otherArgs) => { return fn(...args, ...otherArgs) }; };

Slide 98

Slide 98 text

const partialFromBind = (fn, ...args) => { return fn.bind(null, ...args); }; const partial = (fn, ...args) => { return (...otherArgs) => { return fn(...args, ...otherArgs) }; };

Slide 99

Slide 99 text

const partialFromBind = (fn, ...args) => { return fn.bind(null, ...args); }; const partial = (fn, ...args) => { return (...otherArgs) => { return fn(...args, ...otherArgs) }; };

Slide 100

Slide 100 text

const partialFromBind = (fn, ...args) => { return fn.bind(null, ...args); }; const partial = (fn, ...args) => { return (...otherArgs) => { return fn(...args, ...otherArgs) }; };

Slide 101

Slide 101 text

CURRYING

Slide 102

Slide 102 text

const add3 = add(3); add3(2) === 5; const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); const usersPromise = customRequest({ url: '/users' }); const tasksPromise = customRequest({ url: '/tasks' });

Slide 103

Slide 103 text

const add3 = add(3); add3(2) === 5; const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); const usersPromise = customRequest({ url: '/users' }); const tasksPromise = customRequest({ url: '/tasks' });

Slide 104

Slide 104 text

const add = x => y => x + y; function add(x) { return function(y) { return x + y; }; }

Slide 105

Slide 105 text

const add = x => y => x + y; function add(x) { return function(y) { return x + y; }; }

Slide 106

Slide 106 text

const add = x => y => x + y; function add(x) { return function(y) { return x + y; }; }

Slide 107

Slide 107 text

const request = defaults => options => { options = Object.assign( {}, defaults, options ); return fetch(options.url, options) .then(resp => resp.json()); };

Slide 108

Slide 108 text

const request = defaults => options => { options = Object.assign( {}, defaults, options ); return fetch(options.url, options) .then(resp => resp.json()); };

Slide 109

Slide 109 text

PIECING IT TOGETHER

Slide 110

Slide 110 text

const map = fn => array => array.map(fn); const multiply = x => y => x * y; const pluck = key => object => object[key]; const discount = multiply(0.98); const tax = multiply(1.0925); const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax));

Slide 111

Slide 111 text

const map = fn => array => array.map(fn); const multiply = x => y => x * y; const pluck = key => object => object[key]; const discount = multiply(0.98); const tax = multiply(1.0925); const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax));

Slide 112

Slide 112 text

const map = fn => array => array.map(fn); const multiply = x => y => x * y; const pluck = key => object => object[key]; const discount = multiply(0.98); const tax = multiply(1.0925); const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax));

Slide 113

Slide 113 text

const map = fn => array => array.map(fn); const multiply = x => y => x * y; const pluck = key => object => object[key]; const discount = multiply(0.98); const tax = multiply(1.0925); const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax));

Slide 114

Slide 114 text

const map = fn => array => array.map(fn); const multiply = x => y => x * y; const pluck = key => object => object[key]; const discount = multiply(0.98); const tax = multiply(1.0925); const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax));

Slide 115

Slide 115 text

const map = fn => array => array.map(fn); const multiply = x => y => x * y; const pluck = key => object => object[key]; const discount = multiply(0.98); const tax = multiply(1.0925); const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax));

Slide 116

Slide 116 text

const map = fn => array => array.map(fn); const multiply = x => y => x * y; const pluck = key => object => object[key]; const discount = multiply(0.98); const tax = multiply(1.0925); const customRequest = request({ headers: { 'X-Custom': 'mykey' } }); customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax));

Slide 117

Slide 117 text

customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax)); [ { price: 5 }, { price: 10 }, { price: 3 }, ]

Slide 118

Slide 118 text

[ { price: 5 }, { price: 10 }, { price: 3 }, ] map(pluck('price')) [ 5, 10, 3, ] item.price

Slide 119

Slide 119 text

[ 5, 10, 3, ] map(discount) [ 4.9, 9.8, 2.94, ] price * 0.98

Slide 120

Slide 120 text

[ 5.35, 10.71, 3.21, ] map(tax) [ 4.9, 9.8, 2.94, ] price * 1.0925

Slide 121

Slide 121 text

COMPOSING CLOSURES

Slide 122

Slide 122 text

No content

Slide 123

Slide 123 text

const processWord = compose(hyphenate, reverse, toUpperCase); const words = [ 'hello', 'functional', 'programming' ]; const newWords = words.map(processWord); console.log(newWords); // ['OL-LEH, 'LANOI-TCNUF', 'GNIMM-ARGORP']

Slide 124

Slide 124 text

const processWord = compose(hyphenate, reverse, toUpperCase); const words = [ 'hello', 'functional', 'programming' ]; const newWords = words.map(processWord); console.log(newWords); // ['OL-LEH, 'LANOI-TCNUF', 'GNIMM-ARGORP']

Slide 125

Slide 125 text

const processWord = compose(hyphenate, reverse, toUpperCase); const processWordExplicit = (word) => { return hyphenate(reverse(toUpperCase(word))); };

Slide 126

Slide 126 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) );

Slide 127

Slide 127 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) );

Slide 128

Slide 128 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) );

Slide 129

Slide 129 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) );

Slide 130

Slide 130 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) );

Slide 131

Slide 131 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) );

Slide 132

Slide 132 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) ); fns = [hyphenate, reverse, toUpperCase] arg = result = 'hello'

Slide 133

Slide 133 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) ); fns = [hyphenate, reverse] result = 'HELLO'

Slide 134

Slide 134 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) ); fns = [hyphenate] result = 'OLLEH'

Slide 135

Slide 135 text

const compose = (...fns) => arg => ( fns.reduceRight( (result, fn) => fn(result), arg ) ); fns = [] result = 'OL-LEH'

Slide 136

Slide 136 text

customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax)); RETURNING TO PRICES EXAMPLE

Slide 137

Slide 137 text

customRequest({ url: '/cart/items' }) .then(map(pluck('price'))) .then(map(discount)) .then(map(tax)); Triple iteration RETURNING TO PRICES EXAMPLE

Slide 138

Slide 138 text

customRequest({ url: '/cart/items' }) .then(map( compose( tax, discount, pluck('price') ) )); Single iteration

Slide 139

Slide 139 text

RECURSION SOLVE A PROBLEM IN TERMS OF ITSELF

Slide 140

Slide 140 text

FACTORIAL

Slide 141

Slide 141 text

const factorial = (n) => { let result = 1; while (n > 1) { result *= n; n--; } return result; };

Slide 142

Slide 142 text

const factorial = (n) => { if (n < 2) { return 1; } return n * factorial(n - 1); };

Slide 143

Slide 143 text

const factorial = (n) => { if (n < 2) { return 1; } return n * factorial(n - 1); }; Recursive call

Slide 144

Slide 144 text

const factorial = (n) => { if (n < 2) { return 1; } return n * factorial(n - 1); }; Base case

Slide 145

Slide 145 text

factorial(4);

Slide 146

Slide 146 text

factorial(4); 4 * factorial(3);

Slide 147

Slide 147 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2);

Slide 148

Slide 148 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1);

Slide 149

Slide 149 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1;

Slide 150

Slide 150 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2;

Slide 151

Slide 151 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6;

Slide 152

Slide 152 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24;

Slide 153

Slide 153 text

STEPS Find the recurrence
 (n × n-1 × n-2 × … 1)
 Find the base case
 (n < 2)

Slide 154

Slide 154 text

PERFORMANCE RECURSION

Slide 155

Slide 155 text

const value = factorial(100000); console.log(value); // ??? WHAT IS THE RESULT?

Slide 156

Slide 156 text

const value = factorial(100000); console.log(value); // ??? WHAT IS THE RESULT? RangeError: Maximum call stack size exceeded

Slide 157

Slide 157 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; Call Stack

Slide 158

Slide 158 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; factorial(4) Call Stack

Slide 159

Slide 159 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; factorial(4) factorial(3) Call Stack

Slide 160

Slide 160 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; factorial(4) factorial(3) factorial(2) Call Stack

Slide 161

Slide 161 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; factorial(4) factorial(3) factorial(2) factorial(1) Call Stack

Slide 162

Slide 162 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; factorial(4) factorial(3) factorial(2) Call Stack

Slide 163

Slide 163 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; factorial(4) factorial(3) Call Stack

Slide 164

Slide 164 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; factorial(4) Call Stack

Slide 165

Slide 165 text

factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4 * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; Call Stack

Slide 166

Slide 166 text

const value = factorial(100000); console.log(value); // ??? 100,000 calls = 100,000 stack frames 1 stack frame ≈ 48B Max stack usage ≈ 1MB 100,000 x 48 / 1024 / 1024 = 4.58MB > 1MB

Slide 167

Slide 167 text

IN ES2015!* *SAFARI, CHROME WITH FLAG, NODE WITH FLAG TAIL CALL OPTIMIZATION

Slide 168

Slide 168 text

REPLACE STACK FRAMES

Slide 169

Slide 169 text

const factorial = (n) => { if (n < 2) { return 1; } return n * factorial(n - 1); }; UNOPTIMIZABLE

Slide 170

Slide 170 text

const factorial = (n) => { if (n < 2) { return 1; } return n * factorial(n - 1); }; 1 UNOPTIMIZABLE

Slide 171

Slide 171 text

const factorial = (n) => { if (n < 2) { return 1; } return n * factorial(n - 1); }; 1 UNOPTIMIZABLE 2

Slide 172

Slide 172 text

const factorial = (n) => { if (n < 2) { return 1; } return n * factorial(n - 1); }; 1 UNOPTIMIZABLE 2 3

Slide 173

Slide 173 text

const factorial = (n, accum = 1) => { if (n < 2) { return accum; } return factorial(n - 1, n * accum); }; OPTIMIZABLE

Slide 174

Slide 174 text

const factorial = (n, accum = 1) => { if (n < 2) { return accum; } return factorial(n - 1, n * accum); }; OPTIMIZABLE

Slide 175

Slide 175 text

const factorial = (n, accum = 1) => { if (n < 2) { return accum; } return factorial(n - 1, n * accum); }; OPTIMIZABLE

Slide 176

Slide 176 text

const factorial = (n, accum = 1) => { if (n < 2) { return accum; } return factorial(n - 1, n * accum); }; OPTIMIZABLE

Slide 177

Slide 177 text

const factorial = (n, accum = 1) => { if (n < 2) { return accum; } return factorial(n - 1, n * accum); }; 1 OPTIMIZABLE

Slide 178

Slide 178 text

const factorial = (n, accum = 1) => { if (n < 2) { return accum; } return factorial(n - 1, n * accum); }; 1 2 OPTIMIZABLE

Slide 179

Slide 179 text

const factorial = (n, accum = 1) => { if (n < 2) { return accum; } return factorial(n - 1, n * accum); }; 1 2 3 OPTIMIZABLE

Slide 180

Slide 180 text

const value = factorial(100000); console.log(value); // Infinity

Slide 181

Slide 181 text

factorial(4 /*, 1 */); factorial(3, 4); factorial(2, 12); factorial(1, 24); 24; Call Stack

Slide 182

Slide 182 text

factorial(4 /*, 1 */); factorial(3, 4); factorial(2, 12); factorial(1, 24); 24; factorial(4, 1) Call Stack

Slide 183

Slide 183 text

factorial(4 /*, 1 */); factorial(3, 4); factorial(2, 12); factorial(1, 24); 24; factorial(3, 4) Call Stack

Slide 184

Slide 184 text

factorial(4 /*, 1 */); factorial(3, 4); factorial(2, 12); factorial(1, 24); 24; factorial(2, 12) Call Stack

Slide 185

Slide 185 text

factorial(4 /*, 1 */); factorial(3, 4); factorial(2, 12); factorial(1, 24); 24; factorial(1, 24) Call Stack

Slide 186

Slide 186 text

factorial(4 /*, 1 */); factorial(3, 4); factorial(2, 12); factorial(1, 24); 24; Call Stack

Slide 187

Slide 187 text

RECAP PREDICTABLE SAFE TRANSPARENT MODULAR

Slide 188

Slide 188 text

RESOURCES

Slide 189

Slide 189 text

drboolean.gitbooks.io/mostly-adequate-guide Brian Lonsdorf

Slide 190

Slide 190 text

ES6/7/LATER babeljs.io

Slide 191

Slide 191 text

LANGUAGES Elm (elm-lang.org) Clojurescript (github.com/clojure/clojurescript) Purescript (purescript.org)

Slide 192

Slide 192 text

LIBRARIES Lodash (lodash.com) Ramda (ramdajs.com) RxJS (reactivex.io/rxjs) Immutable.js (facebook.github.io/immutable-js)

Slide 193

Slide 193 text

“MV*” React (facebook.github.io/react) Redux (redux.js.org)

Slide 194

Slide 194 text

QUESTIONS?

Slide 195

Slide 195 text

THANKS! Code: github.com/jfairbank/fp-basics-in-es6 Slides: bit.ly/codestock-17-fp-basics Jeremy Fairbank @elpapapollo / jfairbank