Created
April 1, 2015 15:02
-
-
Save raganwald/8354592291a2eef74247 to your computer and use it in GitHub Desktop.
anyPartialApplication
This file contains 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
const div = (verbed, numerator, denominator) => | |
`${numerator} ${verbed} ${denominator} is ${numerator/denominator}` | |
div('divided by', 1, 3) | |
//=> 1 divided by 3 is 0.3333333333333333 | |
const anyPartialApplication = (() => { | |
const placeholder = {}, | |
anyPartialApplication = (fn, ...template) => { | |
let remainingArgIndex = 0; | |
const mapper = template.map((templateArg) => | |
templateArg === placeholder | |
? ((i) => (args) => args[i])(remainingArgIndex++) | |
: (args) => templateArg); | |
return function (...remainingArgs) { | |
const composedArgs = mapper.map(f => f(remainingArgs)); | |
return fn.apply(this, composedArgs); | |
} | |
}; | |
anyPartialApplication._ = placeholder; | |
return anyPartialApplication; | |
})(); | |
const _ = anyPartialApplication._; | |
const dividedByThree = anyPartialApplication(div, 'divided by', _, 3); | |
dividedByThree(2) | |
//=> 2 divided by 3 is 0.6666666666666666 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment