snippetjavascriptTip
How can I partially apply a function in JavaScript?
Viewed 0 times
javascripthowapplypartiallycanfunction
Problem
Partial application is a technique used to fix a number of arguments to a function, producing another function of smaller arity. This is particularly useful in situations where you want to create a new function by pre-filling some of the arguments of an existing function.
Depending on the function you want to partially apply, you can either prepend or append the arguments to the function. Both techniques are fairly similar.
In order to partially apply a function by prepending arguments, you can use the spread operator (
Similarly, you can partially apply a function by appending arguments using the spread operator (
Depending on the function you want to partially apply, you can either prepend or append the arguments to the function. Both techniques are fairly similar.
In order to partially apply a function by prepending arguments, you can use the spread operator (
...) to prepend partials to the list of arguments of fn. Simply pass partials before any other arguments that are supplied.Similarly, you can partially apply a function by appending arguments using the spread operator (
...). You need only pass them to fn after any other arguments that are supplied.Solution
const partial = (fn, ...partials) => (...args) => fn(...partials, ...args);
const greet = (greeting, name) => greeting + ' ' + name + '!';
const greetHello = partial(greet, 'Hello');
greetHello('John'); // 'Hello John!'In order to partially apply a function by prepending arguments, you can use the spread operator (
...) to prepend partials to the list of arguments of fn. Simply pass partials before any other arguments that are supplied.Similarly, you can partially apply a function by appending arguments using the spread operator (
...). You need only pass them to fn after any other arguments that are supplied.Code Snippets
const partial = (fn, ...partials) => (...args) => fn(...partials, ...args);
const greet = (greeting, name) => greeting + ' ' + name + '!';
const greetHello = partial(greet, 'Hello');
greetHello('John'); // 'Hello John!'const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials);
const greet = (greeting, name) => greeting + ' ' + name + '!';
const greetJohn = partialRight(greet, 'John');
greetJohn('Hello'); // 'Hello John!'Context
From 30-seconds-of-code: partially-apply-function
Revisions (0)
No revisions yet.