Increasing code
reusability through
partial application
Sobre
Derek Stavis
Software Engineer @ Pagar.me
github.com/derekstavis
Agenda
● Motivation
● Partial application
● ES6 implementation
● Use cases
Motivation
If you love to write generic code
function create (db, coll, doc) {
return db[coll].insert(doc)
}
Motivation
If you want to run away from points
const db = client.connect(...)
const createUser = (???) =>
create(db, ‘user’, ???)
Motivation
If you want to run away from points
const db = client.connect(...)
const createUser = (doc) =>
create(db, ‘user’, doc)
Motivation
If you want to run away from points
const db = client.connect(...)
const createUser = (user) =>
create(db, ‘user’, user)
Motivation
You will probably love partial application
const db = client.connect(...)
const createUser =
partial(create, db, ‘user’)
Partial application
Fill the arguments of a function
create(db, coll, doc)
Partial application
Fill the arguments of a function
createInDB = partial(db, create)
createInDB(coll, doc)
The implementation
A rudimentar version written in ES6
(f, ...left) =>
(...right) =>
f(...left, ...right)
Use cases
Dependency injection
HOF and FCF makes DI just simple
healthCheck()
.then(partial(req.status, 200))
.catch(partial(req.status, 500))
Lazy evaluation
Create thunks for lazy functions
const lazyHandle =
partial(handle, req, res, next)
You said... Promises?
Use partial application with chaining
return fetchUser(id)
.then(partial(map, getName))
.then(console.log)
Real use case
Pagar.me Library
https://github.com/pagarme/pagarme-js
Thanks

TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had a SRE team at - Increasing code reusability through partial application