Partial Function with Placeholders - Problem
Create a powerful partial application function that transforms any function into one with pre-filled arguments! Your task is to implement a function that takes a base function fn and an array of arguments args (which may contain placeholder symbols "_"), and returns a new function partialFn.
When partialFn is called with restArgs, it should:
- Replace each
"_"placeholder inargswith values fromrestArgs(in order) - Append any remaining
restArgsto the end of the modified argument list - Call the original function
fnwith all these arguments
Example: If args = [1, "_", 3, "_"] and you call partialFn(5, 7, 9), the placeholders get filled: [1, 5, 3, 7] and the remaining 9 gets appended: [1, 5, 3, 7, 9]
Input & Output
basic_replacement.js โ JavaScript
$
Input:
fn = (a,b,c,d,e) => a+b+c+d+e, args = [1, '_', 3, '_'], restArgs = [5, 7, 9]
โบ
Output:
25
๐ก Note:
The placeholders '_' are replaced with [5, 7] in order, creating [1, 5, 3, 7]. The remaining 9 is appended, giving [1, 5, 3, 7, 9]. Calling fn(1, 5, 3, 7, 9) returns 1+5+3+7+9 = 25.
no_placeholders.js โ JavaScript
$
Input:
fn = (a,b,c) => a*b*c, args = [2, 3, 4], restArgs = [5, 6]
โบ
Output:
240
๐ก Note:
No placeholders to replace, so restArgs [5, 6] are appended to args [2, 3, 4], creating [2, 3, 4, 5, 6]. However, fn only uses first 3 parameters, so fn(2, 3, 4) = 2*3*4 = 24... wait, that would call fn(2,3,4,5,6) = 2*3*4 = 24. Actually it depends on function definition.
more_placeholders_than_args.js โ JavaScript
$
Input:
fn = (...args) => args.join('-'), args = ['_', '_', '_'], restArgs = ['a', 'b']
โบ
Output:
"a-b-_"
๐ก Note:
Only first 2 placeholders can be filled with ['a', 'b'], leaving the third placeholder '_' unchanged. Result is ['a', 'b', '_'], which joins to 'a-b-_'.
Constraints
-
fnis a valid JavaScript function -
argsis an array that may contain any values including placeholder"_" -
restArgsprovided to the returned partial function can be any number of arguments -
1 โค
args.lengthโค 103 -
0 โค number of placeholders โค
args.length -
The returned partial function must work with any number of
restArgs
Visualization
Tap to expand
Understanding the Visualization
1
Template Setup
Start with story template containing blanks '_' and a list of words to fill in
2
Sequential Filling
Go through template left-to-right, filling each blank with next available word
3
Append Extras
Add any remaining words to the end of the story
4
Execute Story
Read the complete story (call the function) with all words in place
Key Takeaway
๐ฏ Key Insight: Just like filling a Mad Libs template, we process placeholders sequentially in one pass, making this both intuitive and optimal with O(n) time complexity!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code