Created
November 15, 2015 18:39
-
-
Save NickHeiner/a42eb90a5f462f8b39ff to your computer and use it in GitHub Desktop.
Examples of functions returning functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// One classic purpose of a function returning a function is to do partial application. | |
// Let's say we have a function that adds two numbers: | |
function add(x, y) { | |
return x + y; | |
} | |
// Then, we want to make a function that adds 9000 to the argument: | |
function itsOver9000(x) { | |
return add(9000, x); | |
} | |
// But what if we weren't happy just adding 9000, | |
// but wanted a way to more generally create functions that add a constant amount to their input? | |
function createAdder(constantAmountToAdd) { | |
return function(x) { | |
return add(constantAmountToAdd, x); | |
}; | |
} | |
// You would use it like so: | |
const addTwo = createAdder(2); | |
addTwo(5); // ==> 7 | |
addTwo(10); // ==> 12 | |
const addNineThousand = createAdder(9000); | |
addNineThousand(1); // ==> 9001 | |
addNineThousand(-1); // ==> -8999 | |
// With a simple function that takes two arguments and adds them, it can seem a little silly | |
// do to all this. What are we really getting? But when the arguments get more complicated, | |
// the benefits from this become more compelling. | |
// For instance, let's say that we have a function that saves to a database: | |
function save(databaseConnectionOptions, dataToSave) { | |
// https://www.youtube.com/watch?v=Qtb11P1FWnc | |
} | |
// We don't want to have to pass the database connection options all around the app. | |
// These connection options could include sensitive information like credentials, | |
// so we want to limit them to as small a part of the program as possible. It's | |
// also just cumbersome to have to make that information available anywhere you want | |
// to save some data. Instead, we'll use partial application to save the connection | |
// options up front: | |
function createSaveFunctionWithConnectionOptionsApplied(databaseConnectionOptions) { | |
return function(dataToSave) { | |
return save(databaseConnectionOptions, dataToSave); | |
}; | |
} | |
// First, we create the function: | |
const saveData = createSaveFunctionWithConnectionOptionsApplied({user: 'admin', password: 'gohan'}); | |
// Then, we can save without worrying about credentials: | |
saveData({username: 'Rust', booksRead: ['Atlas Shrugged']}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment