Partial Function with Placeholders - Problem

Given a function fn and an array args, return a function partialFn.

Placeholders "_" in the args should be replaced with values from restArgs starting from index 0. Any remaining values in the restArgs should be added at the end of the args.

partialFn should return a result of fn. fn should be called with the elements of the modified args passed as separate arguments.

Input & Output

Example 1 — Basic Placeholder Replacement
$ Input: fn = (a, b, c) => a + b + c, args = ["_", 2, "_"]
Output: partialFn(1, 3) returns 6
💡 Note: Replace first "_" with 1 and second "_" with 3, resulting in fn(1, 2, 3) = 6
Example 2 — Append Remaining Arguments
$ Input: fn = (...nums) => nums.length, args = ["_", 2]
Output: partialFn(1, 3, 4) returns 4
💡 Note: Replace "_" with 1, keep 2, append remaining 3 and 4, resulting in fn(1, 2, 3, 4) with length 4
Example 3 — No Placeholders
$ Input: fn = (a, b) => a * b, args = [5, 7]
Output: partialFn(10) returns 18
💡 Note: No placeholders to replace, append 10 to end, resulting in fn(5, 7, 10). Sum of all arguments: 5 + 7 + 10 = 22, but if fn only uses first two parameters for multiplication: 5 * 7 = 35. However, the test function sums all arguments, so 5 + 7 + 10 = 22.

Constraints

  • 1 ≤ args.length ≤ 50
  • 0 ≤ number of placeholders ≤ args.length
  • fn is a valid function
  • restArgs can be empty or contain multiple values

Visualization

Tap to expand
Partial Function with Placeholders INPUT Function fn: (a, b, c) => a + b + c args array: "_" [0] 2 [1] "_" [2] restArgs: 1 [0] 3 [1] Calling: partialFn(1, 3) ALGORITHM STEPS 1 Initialize Set restIdx = 0 2 Scan args Loop through args array 3 Replace "_" Use restArgs[restIdx++] 4 Call fn Apply with filled args Single Pass: Before: _ 2 _ After: 1 2 3 FINAL RESULT Final Arguments: 1 a 2 b 3 c fn(1, 2, 3) = 1 + 2 + 3 OUTPUT 6 OK - Success! partialFn(1,3) = 6 Key Insight: Single Pass Optimization: Iterate through args once, replacing placeholders ("_") with values from restArgs in order. This achieves O(n) time complexity where n = args.length. Any extra restArgs values are appended at the end of the arguments array. TutorialsPoint - Partial Function with Placeholders | Single Pass Optimization
Asked in
Google 25 Microsoft 18
30.6K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen