Skip to content

Instantly share code, notes, and snippets.

@raganwald
Created April 1, 2015 15:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raganwald/8354592291a2eef74247 to your computer and use it in GitHub Desktop.
Save raganwald/8354592291a2eef74247 to your computer and use it in GitHub Desktop.
anyPartialApplication
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