AI solution for JavaScript Coding Question on BFE.dev
139. implement _.partial()
Here's one possible implementation of partial()
in JavaScript:
const partial = (fn, ...presetArgs) => { const placeholder = Symbol() return function partiallyApplied(...laterArgs) { const allArgs = presetArgs.map(arg => arg === partial.placeholder ? laterArgs.shift() : arg).concat(laterArgs) return fn.apply(this, allArgs) }}partial.placeholder = Symbol()// test codeconst func = (...args) => argsconst func123 = partial(func, 1, 2, 3)console.log(func123(4)) // should print [1, 2, 3, 4]const _ = partial.placeholderconst func1_3 = partial(func, 1, _, 3)console.log(func1_3(2, 4)) // should print [1, 2, 3, 4]
The partial()
function takes a function fn
and any number of presetArgs
that are bound to the function's parameters. It returns a new function that takes some additional laterArgs
, which are appended to the preset arguments to form a complete argument list for the original function call.
The key feature of this implementation is support for placeholders, which are stored in a special Symbol
object that's attached to the partial()
function as a property called placeholder
. The partiallyApplied()
function checks each of its presetArgs
and, if it encounters a placeholder, it pops the next value from the laterArgs
array and uses that value in place of the placeholder. If there are no more values left in laterArgs
, the placeholder remains unchanged.
Note that we define partial.placeholder = Symbol()
so that the test code can use _
as a shorthand for partial.placeholder
. Alternatively, we could simply have used undefined
or some other distinctive value as our placeholder symbol.