Lodash partial Argument Execution Priority
When working with functional composition in Lodash, the
_.partial method creates a new function with predefined
arguments. In terms of execution priority, partially applied arguments
take precedence by occupying the initial positions of the target
function's parameter list, while runtime arguments are appended
afterward. However, this left-to-right priority order can be altered
using placeholders, which allow runtime arguments to fill specific slots
before unassigned arguments are appended to the end.
Default Argument Precedence
Under normal operation, _.partial establishes a fixed
left-to-right argument order. The arguments supplied during the
definition of _.partial are placed at the beginning of the
parameter list (index 0, 1, 2, and so on).
When the resulting partially applied function is invoked, any arguments passed at runtime are appended after the partially applied ones:
const _ = require('lodash');
function showOrder(a, b, c) {
console.log(`a: ${a}, b: ${b}, c: ${c}`);
}
// Partially apply 'first' to parameter 'a'
const partialFn = _.partial(showOrder, 'first');
// Runtime arguments 'second' and 'third' fill 'b' and 'c'
partialFn('second', 'third');
// Output: a: first, b: second, c: thirdIn this model, the partially applied arguments hold higher positional priority over runtime arguments.
Altering Priority with Placeholders
Lodash allows you to override default positional precedence by using
placeholders (_ or _.partial.placeholder).
When a placeholder is present in the partial application call, Lodash
alters the resolution priority:
- Placeholder Resolution: Runtime arguments are first
consumed left-to-right to replace any placeholders defined in
_.partial. - Trailing Arguments: Once all placeholders are filled, any remaining runtime arguments are appended to the end of the argument list.
// Reserve the first parameter with a placeholder
const partialWithHole = _.partial(showOrder, _, 'second');
// 'first' fills the placeholder; 'third' is appended to the end
partialWithHole('first', 'third');
// Output: a: first, b: second, c: thirdContrast with
_.partialRight
If your implementation requires runtime arguments to take positional
priority from the beginning of the parameter list, Lodash provides
_.partialRight. With _.partialRight, the
partially applied arguments are appended to the tail of the parameter
list, allowing runtime arguments to populate the initial parameters
first:
const partialRightFn = _.partialRight(showOrder, 'third');
partialRightFn('first', 'second');
// Output: a: first, b: second, c: thirdSummary of Priority Rules
- Fixed Partial Arguments: Bound to specific positions from left to right at initialization.
- Placeholders: Receive the highest priority for incoming runtime arguments until all placeholders are satisfied.
- Runtime Arguments: First fill placeholders in sequential order, then populate any remaining parameters at the end of the argument list.