Skip to content

Instantly share code, notes, and snippets.

View jbmilgrom's full-sized avatar

Jonathan Milgrom jbmilgrom

View GitHub Profile
@jbmilgrom
jbmilgrom / BankAccount.stateful.closure.js
Last active March 7, 2020 21:25
Subsequent calls to withdraw with the same argument produce different results
const bankAccount = makeBankAccount(100);
bankAccount.checkBalance(); // 100
bankAccount.withdraw(20);
bankAccount.checkBalance(); // 80
@jbmilgrom
jbmilgrom / BankAccount.arrowSyntax.js
Last active March 7, 2020 21:23
Show the use of arrow syntax in maintaining state
const makeBankAccount = balance => ({
withdraw: amount => balance = balance - amount,
checkBalance: () => balance
});
import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
main =
Browser.sandbox { init = 0, update = update, view = view }
type Msg = Increment | Decrement
update msg model =
@jbmilgrom
jbmilgrom / withdraw.assignment.js
Last active February 29, 2020 16:23
Example of mutative method
class BankAccount {
...
public withdraw(amount) {
this.balance = this.balance - amount;
}
...
}
@jbmilgrom
jbmilgrom / atm-program.function.js
Created February 28, 2020 17:06
Body of a functional program
const withdraw = (balance, amount) => balance - amount;
const ATM = (state = {balance: 100, amount: 10}, event) => {
switch (event.type) {
case 'WITHDRAW':
return {
...state,
balance: withdraw(state.balance, state.amount),
};
case 'WITHDRAWAL_AMOUNT':
let balance = 100;
balance = balance - 20;
@jbmilgrom
jbmilgrom / withdraw.plop.js
Last active January 19, 2020 15:55
Methods mutate variables nevertheless
const bankAccount = new BankAccount(100); // (this.balance = 100)
bankAccount.withdraw(20); // (this.balance = this.balance - 20)
@jbmilgrom
jbmilgrom / balance.imperative.js
Last active January 12, 2020 23:23
Imperative manipulation of variables
let balance = 100;
balance = balance - 20; // Does this represent a withdrawal or something else entirely?
@jbmilgrom
jbmilgrom / bankAccount.behavior.js
Created January 5, 2020 14:24
Object and behavior association
bankAccount.withdraw(20);
@jbmilgrom
jbmilgrom / functionComposition.higherOrder.js
Last active January 3, 2020 22:58
Example of function composition with higher-order function 'reduce'
const square = x => x * x;
const sum = (x, y) => x + y;
const sumOfSquares = (...nums) => nums.reduce((total, num) => sum(total, square(num)), 0);
sumOfSquares(1, 2, 3); // 14