Skip to content

Instantly share code, notes, and snippets.

View jbmilgrom's full-sized avatar

Jonathan Milgrom jbmilgrom

View GitHub Profile
@jbmilgrom
jbmilgrom / factorial.iterative.functional.js
Last active December 24, 2019 20:27
Functional, iterative, factorial implementation
const factorial = n => {
const iterate = (total, i) => {
if (i === 0) return total;
return iterate(total * i, i - 1);
}
return iterate(1, n);
};
factorial(0); // => 1
factorial(1); // => 1
@jbmilgrom
jbmilgrom / BankAccount.imperative.js
Created November 29, 2019 21:04
Imperatively maintained "bank account"
let bankAccount = 100;
bankAccount = bankAccount - 20;
bankAccount; // 80
@jbmilgrom
jbmilgrom / BankAccount.assignment.js
Created November 29, 2019 18:16
Highlight assignment of variable in closure construction
const makeBankAccount = balance => ({
withdraw: amount => balance = balance - amount, // <-- assign `balance` a new value
checkBalance: () => balance
});
const bankAccount = makeBankAccount(100);
bankAccount.withdraw(20);
bankAccount.checkBalance(); // 80
@jbmilgrom
jbmilgrom / BankAccount.assignment.ts
Last active January 5, 2020 01:34
Highlight assignment of variable in class construction
class BankAccount {
private balance;
constructor(funds) {
this.balance = funds;
}
public withdraw(amount) {
this.balance = this.balance - amount; // <-- assign `this.balance` a new value
}
@jbmilgrom
jbmilgrom / factorial.functional.js
Created September 23, 2019 16:42
Iterative process couched in terms of recursive procedure
const factorial = n => {
if (n === 0) return 1;
return n * factorial(n - 1);
};
factorial(1); // => 1
factorial(2); // => 2
factorial(3); // => 6
const factorial = n => {
let total = 1;
while (n > 0) {
total = total * n;
n = n - 1;
}
return total;
};
factorial(0); // => 1
const decrement100 = x => {
let r = 100;
r = 100 - x;
return r;
};
decrement100(20); // => 80
@jbmilgrom
jbmilgrom / buidCallbacks.js
Last active September 23, 2019 13:12
Problems with "internal" mutability
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"]);
@jbmilgrom
jbmilgrom / add.imperative.js
Last active September 22, 2019 21:35
"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
@jbmilgrom
jbmilgrom / listOfStrings.immutable.js
Last active September 24, 2019 13:34
Arbitrary data can be the subject of functional behavior
const space = (w1, w2) => `${w1} ${w2}`;
const sentence = words => `${words.reduce(space)}.`;
sentence(['i', 'heart', 'functions']); // => "i heart functions."