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

Scenic City Summit: Functional Programming Basics in ES6

Scenic City Summit: Functional Programming Basics in ES6

Jeremy Fairbank

August 12, 2016
Tweet

More Decks by Jeremy Fairbank

Other Decks in Programming

Transcript

  1. All good let age = 28; age = 29; const

    name = 'Jeremy'; name = 'Jet'; Syntax error
  2. const add = (x, y) => { return x +

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

    y; }; const identity = x => x;
  4. const array = (...elements) => { return elements; }; array(1,

    2, 3); // [1, 2, 3] const log = (...args) => { console.log(...args); }; log('hello', 'scenic city summit'); // hello scenic city summit
  5. const array = (...elements) => { return elements; }; array(1,

    2, 3); // [1, 2, 3] const log = (...args) => { console.log(...args); }; log('hello', 'scenic city summit'); // hello scenic city summit
  6. const langs = ['JavaScript', 'Ruby', 'Haskell']; const [js, ...rest] =

    langs; js === 'JavaScript'; rest[0] === 'Ruby'; rest[1] === 'Haskell'; const head = ([x]) => x; head([1, 2, 3]) === 1;
  7. const langs = ['JavaScript', 'Ruby', 'Haskell']; const [js, ...rest] =

    langs; js === 'JavaScript'; rest[0] === 'Ruby'; rest[1] === 'Haskell'; const head = ([x]) => x; head([1, 2, 3]) === 1;
  8. const greet = (name, greeting = 'Hi') => { console.log(greeting,

    name); }; greet('Scenic City Summit', 'Hello'); // Hello Scenic City Summit greet('Chattanooga'); // Hi Chattanooga
  9. Object.assign( {}, { hello: 'Chattanooga' }, { hi: 'Scenic City

    Summit' } ); // { // hello: 'Chattanooga', // hi: 'Scenic City Summit' // }
  10. 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; };
  11. const add = (x, y) => x + y; add(2,

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

    3) === 5; add(2, 3) === 5; add(2, 3) === 5; Referentially transparent
  13. × let name = 'Jeremy'; const getName = () =>

    name; const setName = (newName) => { name = newName; }; const printUpperName = () => { console.log(name.toUpperCase()); };
  14. 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'); }); }); ×
  15. const upperName = (name) => name.toUpperCase(); describe('api', () => {

    it('returns an uppercase name', () => { expect(upperName('Jeremy')).to.equal('JEREMY'); expect(upperName('Jet')).to.equal('JET'); }); }); ✓
  16. 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]
  17. const hobbies = [ 'programming', 'reading', 'music' ]; const firstTwo

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

    = hobbies.splice(0, 2); console.log(firstTwo); // ['programming', 'reading'] console.log(hobbies); // ['music'] Slight typo + mutability
  19. 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] ×
  20. 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)
  21. PROS SAFETY FREE UNDO/REDO LOGS — REDUX EXPLICIT FLOW OF

    DATA LESS MEMORY USAGE* CONCURRENCY SAFETY* *In certain cases
  22. CONS VERBOSE MORE OBJECT CREATION* MORE GARBAGE COLLECTION* MORE MEMORY

    USAGE* *Alleviated with libs like Immutable.js
  23. 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);
  24. 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);
  25. 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);
  26. 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);
  27. const createAdder = (x) => { return (y) => x

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

    + y; }; const add3 = createAdder(3); add3(2) === 5; add3(3) === 6;
  29. 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' } });
  30. 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
  31. 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' });
  32. 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' });
  33. const createAdder = (x) => { return (y) => x

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

    add3 = partial(add, 3); add3(2) === 5;
  35. 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' });
  36. const partialFromBind = (fn, ...args) => { return fn.bind(null, ...args);

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

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

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

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

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

    }; const partial = (fn, ...args) => { return (...otherArgs) => { return fn(...args, ...otherArgs) }; };
  42. const add3 = add(3); add3(2) === 5; const customRequest =

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

    request({ headers: { 'X-Custom': 'mykey' } }); const usersPromise = customRequest({ url: '/users' }); const tasksPromise = customRequest({ url: '/tasks' });
  44. const add = x => y => x + y;

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

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

    function add(x) { return function(y) { return x + y; }; }
  47. const request = defaults => options => { options =

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

    Object.assign( {}, defaults, options ); return fetch(options.url, options) .then(resp => resp.json()); };
  49. 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));
  50. 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));
  51. 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));
  52. 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));
  53. 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));
  54. 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));
  55. 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));
  56. [ { price: 5 }, { price: 10 }, {

    price: 3 } ] map(pluck('price')) [ 5, 10, 3 ] item.price
  57. 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']
  58. 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']
  59. const compose = (...fns) => (...args) => { if (fns.length

    === 0) { return args[0]; } const last = fns[fns.length - 1]; const rest = fns.slice(0, -1); return rest.reduceRight((memo, fn) => { return fn(memo); }, last(...args)); };
  60. const compose = (...fns) => (...args) => { if (fns.length

    === 0) { return args[0]; } const last = fns[fns.length - 1]; const rest = fns.slice(0, -1); return rest.reduceRight((memo, fn) => { return fn(memo); }, last(...args)); };
  61. const compose = (...fns) => (...args) => { if (fns.length

    === 0) { return args[0]; } const last = fns[fns.length - 1]; const rest = fns.slice(0, -1); return rest.reduceRight((memo, fn) => { return fn(memo); }, last(...args)); };
  62. const compose = (...fns) => (...args) => { if (fns.length

    === 0) { return args[0]; } const last = fns[fns.length - 1]; const rest = fns.slice(0, -1); return rest.reduceRight((memo, fn) => { return fn(memo); }, last(...args)); };
  63. const factorial = (n) => { let result = 1;

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

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

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

    { return 1; } return n * factorial(n - 1); }; Base case
  67. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

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

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

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

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24;
  71. STEPS Find the recurrence
 (n × n-1 × n-2 ×

    … 1)
 Find the base case
 (n < 2)
  72. const value = factorial(100000); console.log(value); // ??? WHAT IS THE

    RESULT? RangeError: Maximum call stack size exceeded
  73. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> Call Stack
  74. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> factorial(4) Call Stack
  75. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> factorial(4) factorial(3) Call Stack
  76. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> factorial(4) factorial(3) factorial(2) Call Stack
  77. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> factorial(4) factorial(3) factorial(2) factorial(1) Call Stack
  78. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> factorial(4) factorial(3) factorial(2) Call Stack
  79. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> factorial(4) factorial(3) Call Stack
  80. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> factorial(4) Call Stack
  81. factorial(4); 4 * factorial(3); 4 * 3 * factorial(2); 4

    * 3 * 2 * factorial(1); 4 * 3 * 2 * 1; 4 * 3 * 2; 4 * 6; 24; <main> Call Stack
  82. 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
  83. const factorial = (n) => { if (n < 2)

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

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

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

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

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

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

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

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

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

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

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