Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Codestock 2017: Functional Programming Basics in ES6

Codestock 2017: Functional Programming Basics in ES6

Jeremy Fairbank

May 05, 2017
Tweet

More Decks by Jeremy Fairbank

Other Decks in Programming

Transcript

  1. Jeremy Fairbank
    @elpapapollo / jfairbank
    FUNCTIONAL
    PROGRAMMING
    BASICS IN ES6

    View Slide

  2. Software is broken.
    We are here to fix it.
    Say [email protected]

    View Slide

  3. View Slide

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

    View Slide

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

    View Slide

  6. View Slide

  7. Domain to Range

    View Slide

  8. View Slide

  9. View Slide

  10. Domain Range

    View Slide

  11. CALCULUS

    View Slide

  12. PRINCIPLES

    View Slide

  13. PURE & DECLARATIVE
    PREDICTABLE

    View Slide

  14. IMMUTABLE STATE
    SAFE

    View Slide

  15. FIRST CLASS STATE
    TRANSPARENT

    View Slide

  16. COMPOSABLE FIRST
    CLASS CLOSURES
    MODULAR

    View Slide

  17. ES2015
    (ES6)

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  45. 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;
    };

    View Slide

  46. PURE

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  53. 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');
    });
    });
    ×

    View Slide

  54. HIDDEN STATE IS
    UNCERTAIN STATE

    View Slide

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

    View Slide

  56. HOW TO ACHIEVE THE
    RESULT
    IMPERATIVE

    View Slide

  57. 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]

    View Slide

  58. DECLARE WHAT THE
    DESIRED RESULT IS
    DECLARATIVE

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  62. CREATE STATE, DON’T
    MUTATE IT
    IMMUTABLE

    View Slide

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

    View Slide

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

    View Slide

  65. Object.freeze
    Immutable.js

    View Slide

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

    View Slide

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

    View Slide

  68. FREE YOUR
    STATE

    View Slide

  69. 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]
    ×

    View Slide

  70. 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)

    View Slide

  71. 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)

    View Slide

  72. 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)

    View Slide

  73. 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)

    View Slide

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

    View Slide

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

    View Slide

  76. FIRST CLASS
    FUNCTIONS

    View Slide

  77. 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);

    View Slide

  78. 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);

    View Slide

  79. 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);

    View Slide

  80. 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);

    View Slide

  81. ENCAPSULATION
    CLOSURES

    View Slide

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

    View Slide

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

    View Slide

  84. 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' }
    });

    View Slide

  85. 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

    View Slide

  86. 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' });

    View Slide

  87. 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' });

    View Slide

  88. FOUNDATION FOR
    HIGHER ORDER
    PATTERNS
    FIRST CLASS
    CLOSURES

    View Slide

  89. PARTIAL
    APPLICATION

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  93. 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' });

    View Slide

  94. 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' });

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  101. CURRYING

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  109. PIECING IT
    TOGETHER

    View Slide

  110. 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));

    View Slide

  111. 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));

    View Slide

  112. 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));

    View Slide

  113. 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));

    View Slide

  114. 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));

    View Slide

  115. 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));

    View Slide

  116. 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));

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  121. COMPOSING
    CLOSURES

    View Slide

  122. View Slide

  123. 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']

    View Slide

  124. 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']

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  139. RECURSION SOLVE A PROBLEM
    IN TERMS OF ITSELF

    View Slide

  140. FACTORIAL

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  145. factorial(4);

    View Slide

  146. factorial(4);
    4 * factorial(3);

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  153. STEPS
    Find the recurrence

    (n × n-1 × n-2 × … 1)

    Find the base case

    (n < 2)

    View Slide

  154. PERFORMANCE
    RECURSION

    View Slide

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

    View Slide

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

    View Slide

  157. 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

    View Slide

  158. 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

    View Slide

  159. 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

    View Slide

  160. 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

    View Slide

  161. 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

    View Slide

  162. 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

    View Slide

  163. 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

    View Slide

  164. 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

    View Slide

  165. 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

    View Slide

  166. 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

    View Slide

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

    View Slide

  168. REPLACE STACK
    FRAMES

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  181. factorial(4 /*, 1 */);
    factorial(3, 4);
    factorial(2, 12);
    factorial(1, 24);
    24;

    Call Stack

    View Slide

  182. factorial(4 /*, 1 */);
    factorial(3, 4);
    factorial(2, 12);
    factorial(1, 24);
    24;

    factorial(4, 1)
    Call Stack

    View Slide

  183. factorial(4 /*, 1 */);
    factorial(3, 4);
    factorial(2, 12);
    factorial(1, 24);
    24;

    factorial(3, 4)
    Call Stack

    View Slide

  184. factorial(4 /*, 1 */);
    factorial(3, 4);
    factorial(2, 12);
    factorial(1, 24);
    24;

    factorial(2, 12)
    Call Stack

    View Slide

  185. factorial(4 /*, 1 */);
    factorial(3, 4);
    factorial(2, 12);
    factorial(1, 24);
    24;

    factorial(1, 24)
    Call Stack

    View Slide

  186. factorial(4 /*, 1 */);
    factorial(3, 4);
    factorial(2, 12);
    factorial(1, 24);
    24;

    Call Stack

    View Slide

  187. RECAP
    PREDICTABLE
    SAFE
    TRANSPARENT
    MODULAR

    View Slide

  188. RESOURCES

    View Slide

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

    View Slide

  190. ES6/7/LATER
    babeljs.io

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  194. QUESTIONS?

    View Slide

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

    View Slide