JS Built-ins
Closuresintermediate

Closures β€” Partial application

πŸ“– Usage Example
function partial(fn, ...presetArgs) {
  return (...newArgs) => fn(...presetArgs, ...newArgs)
}
const add = (a, b, c) => a + b + c
const addFive = partial(add, 5)
addFive(3, 2)  // β†’ 10

Partial application uses closures to capture preset arguments, returning a new function that completes the call with the remaining arguments.

Pre-fill Function Arguments

Create a function that takes a function and some arguments, then returns a new function where those arguments are pre-filled.

Challenge: Create a partial(fn, ...presetArgs) function that returns a new function. When the new function is called with additional arguments, it calls the original function with the pre-filled arguments followed by the new arguments.

Example:

const add = (a, b, c) => a + b + c
const addFive = partial(add, 5)
addFive(3, 2)     // add(5, 3, 2) = 10
const addTenFive = partial(add, 10, 5)
addTenFive(2)     // add(10, 5, 2) = 17
πŸ’‘ Hints (2)
  • β€’ Use rest parameters to capture preset and new arguments
  • β€’ Return a function that combines both argument sets