Instantly share code, notes, and snippets.

# Jonathan Milgromjbmilgrom

• Sort options
Created Sep 23, 2019
Iterative process couched in terms of recursive procedure
View factorial.functional.js
 const factorial = n => { if (n === 0) return 1; return n * factorial(n - 1); }; factorial(1); // => 1 factorial(2); // => 2 factorial(3); // => 6
Created Sep 23, 2019
View factorial.imperative.js
 const factorial = n => { let f = 1; while (n > 0) { f = f * n; n = n - 1; } return f; }; factorial(1); // => 1
Last active Sep 23, 2019
View decrement100.mutable.js
 const decrement100 = x => { let r = 100; r = 100 - x; return r; }; decrement100(20); // => 80
Last active Sep 23, 2019
Problems with "internal" mutability
View buidCallbacks.js
 const buildCallbacks = items => { const callbacks = []; let i; for (i = 0; i < items.length; i++) { callbacks.push(() => items[i]); } return callbacks; } const callbacks = buildCallbacks(["hello", "cruel", "world"]);
Last active Sep 22, 2019
"functional" semantics with looping construct
 const add10 = n => { let sum = n; for (let i = 0; i < 10; i++) { sum = sum + 1; } return sum; }; add10(2); // => 12 add10(1); // => 11
Last active Sep 24, 2019
Arbitrary data can be the subject of functional behavior
View listOfStrings.immutable.js
 const space = (w1, w2) => `\${w1} \${w2}`; const sentence = words => `\${words.reduce(space)}.`; sentence(['i', 'heart', 'functions']); // => "i heart functions."
Last active Sep 22, 2019
Arbitrary data can be the subject of functional behavior
View strings.immutable.js
 const space = (w1, w2) => `\${w1} \${w2}`; space('hello', 'world'); // => "hello world"
Last active Sep 18, 2019
"sameness" in the context of mutability
View rationalNumbers.mutable.ts
 type RationalNumber = [number /* numerator */, number /* denominator */]; // turn into decimal form before comparing in order to reduce fraction const isEqual = (a: RationalNumber, b: RationalNumber) => (a[0] / a[1]) === (b[0] / b[1]); const r1: RationalNumber = [2, 3]; const r2: RationalNumber = [2, 3]; const r3: RationalNumber = [2, 5]; r2[1] = 5;
Last active Sep 18, 2019
"sameness" in the context of immutability
View rationalNumbers.immutable.ts
 type RationalNumber = readonly [number /* numerator */, number /* denominator */]; // turn into decimal form before comparing in order to reduce fraction const isEqual = (a: RationalNumber, b: RationalNumber) => (a[0] / a[1]) === (b[0] / b[1]); const r1: RationalNumber = [2, 3]; const r2: RationalNumber = [2, 3]; const r3: RationalNumber = [2, 5]; isEqual(r1, r2); // => true
Created Aug 28, 2019
Example of "sameness" in the context of mutability
View pair.mutable.js
 const p1 = [1, 2]; const p2 = [1, 2]; const p3 = [1, 3]; p2[1] = 3; // Which of p1, p2 and p3 are "the same"?
You can’t perform that action at this time.