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

CodeMash: Functional Programming Basics in ES6

CodeMash: Functional Programming Basics in ES6

Jeremy Fairbank

January 07, 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', 'codemash'); // hello codemash
  5. const array = (...elements) => { return elements; }; array(1,

    2, 3); // [1, 2, 3] const log = (...args) => { console.log(...args); }; log('hello', 'codemash'); // hello codemash
  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('Codemash', 'Hello'); // Hello Codemash greet('Sandusky'); // Hi Sandusky
  9. 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; };
  10. const add = (x, y) => x + y; add(2,

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

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

    name; const setName = (newName) => { name = newName; }; const printUpperName = () => { console.log(name.toUpperCase()); };
  13. describe('api', () => { beforeEach(() => mockConsoleLog()); afterEach(() => restoreConsoleLog());

    it('sets and prints the name', () => { printUpperName(); expect(console.log).calledWith('JEREMY'); n.setName('Jet'); printUpperName(); expect(console.log).calledWith('JET'); }); }); ×
  14. const upperName = (name) => name.toUpperCase(); describe('api', () => {

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

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

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

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

    USAGE* *Alleviated with libs like Immutable.js
  22. 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);
  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 createAdder = (x) => { return (y) => x

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

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

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

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

    }; const partial = (fn, ...args) => { return (...otherArgs) => { return fn(...args, ...otherArgs) }; };
  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 add3 = add(3); add3(2) === 5; const customRequest =

    request({ headers: { 'X-Custom': 'mykey' } }); const usersPromise = customRequest({ url: '/users' }); const tasksPromise = customRequest({ url: '/tasks' });
  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 add = x => y => x + y;

    function add(x) { return function(y) { return x + y; }; }
  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 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));
  47. 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));
  48. 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));
  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. [ { price: 5 }, { price: 10 }, {

    price: 3 } ] map(pluck('price')) [ 5, 10, 3 ] item.price
  54. 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']
  55. 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']
  56. 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)); };
  57. 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)); };
  58. 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)); };
  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 factorial = (n) => { let result = 1;

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

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

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

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

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

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

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

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

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

    RESULT? RangeError: Maximum call stack size exceeded
  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; <main> Call Stack
  71. 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
  72. 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
  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> factorial(4) factorial(3) factorial(2) 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) factorial(3) factorial(2) factorial(1) 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) factorial(2) 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) 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) 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> Call Stack
  79. 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
  80. const factorial = (n) => { if (n < 2)

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

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

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

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

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

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

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

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

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

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

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