Email @ ben@vtdesignworks.com
Director of Development @ Vermont Design Works
Adjunct Professor @ Champlain College
Interested in writing apps in React with ES6?
We are hiring front-end and back-end devs!
“Write
programsfunctions that do one thing and do it well. Writeprogramsfunctions to work together.”– Doug McIlroy, inventor of UNIX pipes
To achieve our goal, we need to do 2 things:
This talk looks at techniques for
decomposition and composition.
How do we make this function more re-usable?
var characters = [
{id: 1, name: 'Arrow'},
{id: 2, name: 'Oblio'},
];
var characterIds = characters.map(function(character) {
return character.id;
});
Step 1: Parameterize the Property Name
function get(propName, object) {
return object[propName];
}
var characters = [
{id: 1, name: 'Arrow'},
{id: 2, name: 'Oblio'},
];
var characterIds = characters.map(get); // ?!@#
That was pointless!
Step 2: Make it Fit the Desired Interface
function get(propName, object) {
return object[propName];
}
function getId(object) {
return get('id', object);
}
var characters = [
{id: 1, name: 'Arrow'},
{id: 2, name: 'Oblio'},
];
var characterIds = characters.map(getId);
Manual and quite ugly.
Wouldn't it be nice if we had a way to easily
transform get into getId?
A programming language has first-class functions if...
Step 3: Make get return a function
function get(propName) {
return function(object) {
return object[propName];
};
}
var characters = [
{id: 1, name: 'Arrow'},
{id: 2, name: 'Oblio'},
];
var characterIds = characters.map(get('id'));
Better, but writing nested functions is tedious...
What is the Relationship between these 2 functions?
function getA(propName, object) {
return object[propName];
}
function getB(propName) {
return function(object) {
return object[propName];
};
}
getB takes getA's first argument (propName) and returns a function that takes getA's second argument (object) and returns getA(propName, object)
Can we write a function to turn getA into getB?
function getA(propName, object) {
return object[propName];
}
function ???(getA, arg1) {
return function(arg2) {
return getA(arg1, arg2);
};
}
What do we call it?
Partial Application: Application is calling a function with arguments, partial refers to the fact that we dont have all the arguments yet
function get(propName, object) {
return object[propName];
}
function leftApply(fn, arg1) {
return function(arg2) {
return fn(arg1, arg2);
};
}
const getId = leftApply(get, 'id');
characters.map(getId);
Javascript supports partial application natively.
function get(propName, object) {
return object[propName];
}
const getId = get.bind(null, 'id');
characters.map(getId);
Allows us to write our function normally (immediately evaluating) and have the returning of nested functions handled automatically.
leftApply (and its corollary rightApply) helps us to decompose a function into a simpler function by supplying one of its arguments up front.
Left apply is an example of a higher order function.
Higher Order functions are functions which accept a function as an argument OR return a function as a value.
We can write higher order functions to transform other functions.
characters.map(leftApply(get, 'id'));
characters.map(get('id'));
A technique which turns a function of arity X of into a nested series of X unary (single argument) functions.
var character = { id: 5, name: 'Rock Man' };
get('name', character); // 'Rock Man'
var curriedGet = curry(get);
curriedGet('name')(character); // 'Rock Man'
var getName = curriedGet('name');
getName(character); // 'Rock Man'
Anybody know why its called currying?
Our get function from earlier was a curried function:
function get(propName, obj) {
return obj[propName];
}
function curriedGet(propName) {
return function(obj) {
return obj[propName];
};
}
Curried functions accept 1 argument at a time. You call the returned function with the next argument, etc. When the final argument is supplied, the function is called and the value is returned.
Final Get Function
const get = curry(function get(propName, obj) {
return obj[propName];
});
var characters = [
{id: 3, name: 'The Count'},
{id: 4, name: 'The Pointed Man'},
];
var characterIds = characters.map(get('id'));
Take it Further: Curried Map
const get = curry(function get(propName, obj) {
return obj[propName];
});
const map = curry(function map(fn, mappable) {
return mappable.map(fn);
});
var characters = [
{id: 3, name: 'The Count'},
{id: 4, name: 'The Pointed Man'},
];
const getIds = map(get('id'));
var characterIds = getIds(characters);
Its not just passing functions as args or storing them in vars.
We can use functions that create new functions by breaking down existing functions, like leftApply or curry.
We can also use functions that create new functions by combining existing functions.
This makes sense when we think of functions as values in the same way as we think of numbers or strings as values. We can perform operations on them to combine or transform them and create new values.
# Edit the result of a command in vim
du -h /var | sort -hr | head -10 | vim -
# Create a file and edit it
touch myfile.txt && vim $_
# Open modified files in vim
vim $(git status -uno --porcelain | awk '{ print $2 }')
function logBeforeAdd(x, y) {
console.log(x, y);
return add(x, y);
}
function logBefore(fn) {
return function() {
console.log(arguments);
return fn.apply(this, arguments);
};
}
What is the behavior of the logBefore fn?
A decorator is a higher order function that takes one function as its argument and returns a new function that is closely related to the original function
function logBefore(fn) {
return function() {
console.log(arguments);
return fn.apply(this, arguments);
}
}
Side-effect made explicit & isolated
function retry(fn, maxTries) {
return function() {
var error;
while (maxTries--) {
try {
return fn.apply(this, arguments);
} catch (err) {
error = err;
}
}
throw error;
};
}
const resilientLoadUsers = retry(loadUsers, 3);
const users = resilientLoadUsers();
function memoize(fn) {
var memos = {};
return function() {
var key = JSON.stringify(Array.from(arguments));
if (!memos.hasOwnProperty(key)) {
console.log('cache miss on: '+key);
memos[key] = fn.apply(this, arguments);
} else {
console.log('cache hit on: '+key);
}
return memos[key];
};
};
const memoizedAdd = memoize(add);
memoizedAdd(1, 2); // cache miss on: [1,2]
memoizedAdd(1, 2); // cache hit on: [1,2]
Decouple complex multi-step operation into small, manageable chunks.
function uppercase(string) {
return string.toUpperCase();
}
function pipe() {
const functionQueue = Array.from(arguments);
return function() {
const initialValue = arguments[0];
return functionQueue.reduce(
(returnValue, fn) => return fn(returnValue),
initialValue
);
}
}
const getUppercaseName = pipe(get('name'), uppercase);
const uppercaseNames = characters.map(getUppercaseName);
compose = flip(pipe);
const log = console.log.bind(console);
function logBefore(fn) {
return function() {
log(arguments);
return fn.apply(this, arguments);
};
}
How do we make this more re-usable?
const log = console.log.bind(console);
function before(beforeFn, mainFn) {
return function() {
beforeFn.apply(this, arguments);
return mainFn.apply(this, arguments);
};
}
const logBeforeAdd = before(log, add);
const logBeforeClick = before(log, handleClick);
Can we make this even more re-usable?
const log = console.log.bind(console);
const before = curry(function before(beforeFn, mainFn) {
return function() {
beforeFn.apply(this, arguments);
return fn.apply(this, arguments);
};
});
const logBefore = before(log);
const logBeforeAdd = logBefore(add);
const logBeforeClick = logBefore(handleClick);
Combinators are functions that create more complex values by combining the provided arguments.
We're used to thinking about combining values likes numbers (addition), arrays (concat), or objects (Object.assign), but less so with functions.
before(beforeFn, mainFn) is a function combinator, a higher order function that create more complex functions by combining other functions.
Return the result of calling aroundFn with mainFn and all other arguments. You can implement many decorators using around.
function around(wrapperFn, mainFn) {
return function() {
var args = [mainFn].concat(Array.from(arguments));
return wrapperFn.apply(this, args);
};
}
const addAndDouble = around(function(mainFn, ...args) {
return mainFn(...args) * 2;
}, add);
addAndDouble(1, 2); // 6
Email @ ben@vtdesignworks.com
Director of Development @ Vermont Design Works
Adjunct Professor @ Champlain College
Interested in writing apps in React with ES6?
We are hiring front-end and back-end devs!