Skip to content

Instantly share code, notes, and snippets.

@atticoos
Last active January 10, 2017 06:12
Show Gist options
  • Save atticoos/e0053349b5b74e6051f67173105f67e2 to your computer and use it in GitHub Desktop.
Save atticoos/e0053349b5b74e6051f67173105f67e2 to your computer and use it in GitHub Desktop.
var count = 0;
function increment (amount) {
count = count + 1;
return count;
}
increment(1) // 1
increment(1) // 2
increment(1) // 3
var count = 0;
// now returns a function that becomes called with the count
function increment (amount) {
return function (lastCount) {
count = lastCount + amount;
return count;
}
}
increment(1)(count) // 1
// composable "add 1" incrementer function
// same as:
const incrementByOne = increment(1);
incrementByOne(count) // 2
incrementByOne(count) // 3
incrementByOne(count) // 4
function Store (initialState) {
var state = intiailState;
function transition (transitionFunction) {
state = transitionFunction(state);
return state;
}
return {transition};
}
var countStore = new Store(0);
// no longer set the count, we just return the incremented count
function increment (amount) {
return function (count) {
return count + amount;
}
}
countStore.transition(increment(1)) // 1
// same as:
const incrementByOne = increment(1);
countStore.transition(incrementByOne) // 2
countStore.transition(incrementByOne) // 3
countStore.transition(incrementByOne) // 4
@atticoos
Copy link
Author

atticoos commented Jan 10, 2017

Currying - allows a function to be executed from multiple callsites, where each callsite can provide its own input

W/o currying:

function increment (count, amount) {
  return count + amount;
}

// only callable in one place
increment(1, 1)

W/ currying:

function increment (amount) {
  return function (count) {
    return count + amount;
  }
}

// first call, right here
const incrementByOne = increment(1);

// second call, somewhere else
store.transition(incrementByOne)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment