Problem Statement
What is partial application?
Explanation
Partial application creates a new function by pre-filling some arguments of an existing function.
It is different from currying. Currying transforms a multi-argument function into nested single-argument functions. Partial application fixes some arguments and returns a function that takes remaining arguments.
Partial application uses bind or custom functions to fix arguments.
It creates specialized functions from generic ones.
Partial application improves code reusability and readability.
It is commonly used for creating utility functions.
Code Solution
SolutionRead Only
// Original function
function multiply(a, b, c) {
return a * b * c;
}
// Partial application with bind
const multiplyBy2 = multiply.bind(null, 2);
console.log(multiplyBy2(3, 4)); // 2 * 3 * 4 = 24
const multiplyBy2And3 = multiply.bind(null, 2, 3);
console.log(multiplyBy2And3(4)); // 2 * 3 * 4 = 24
// Custom partial function
function partial(fn, ...fixedArgs) {
return function(...remainingArgs) {
return fn(...fixedArgs, ...remainingArgs);
};
}
const double = partial(multiply, 2, 1);
console.log(double(5)); // 2 * 1 * 5 = 10
// Practical example - logging
function log(level, timestamp, message) {
console.log(`[${level}] ${timestamp}: ${message}`);
}
// Create specialized loggers
const errorLogger = partial(log, 'ERROR');
const infoLogger = partial(log, 'INFO');
errorLogger('2024-01-01', 'Something went wrong');
// [ERROR] 2024-01-01: Something went wrong
infoLogger('2024-01-01', 'App started');
// [INFO] 2024-01-01: App started
// API request example
function fetch(method, url, options) {
console.log(`${method} ${url}`, options);
}
const get = partial(fetch, 'GET');
const post = partial(fetch, 'POST');
const put = partial(fetch, 'PUT');
get('/api/users', { headers: {} });
post('/api/users', { body: {name: 'John'} });
// Difference from currying
// Currying
const curriedMultiply = a => b => c => a * b * c;
console.log(curriedMultiply(2)(3)(4)); // Must call with one arg at a time
// Partial application
const partialMultiply = partial(multiply, 2);
console.log(partialMultiply(3, 4)); // Can call with multiple args
// Combining with composition
const add = (a, b) => a + b;
const addFive = partial(add, 5);
const multiplyByTwo = x => x * 2;
const addFiveAndDouble = pipe(addFive, multiplyByTwo);
console.log(addFiveAndDouble(10)); // (10 + 5) * 2 = 30
// Event handler example
function handleClick(prefix, event) {
console.log(prefix, event.target);
}
const handleButtonClick = partial(handleClick, 'Button clicked:');
// button.addEventListener('click', handleButtonClick);