2797. Partial Function with Placeholders π
Description
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.
Β
Example 1:
Input: fn = (...args) => args, args = [2,4,6], restArgs = [8,10] Output: [2,4,6,8,10] Explanation: const partialFn = partial(fn, args) const result = partialFn(...restArgs) console.log(result) //Β [2,4,6,8,10] There are no placeholders "_" in args therefore restArgs is just added at the end of args. Then the elements of theΒ argsΒ are passed as separate arguments to fn, which returns passed arguments as an array.
Example 2:
Input: fn = (...args) => args, args = [1,2,"_",4,"_",6], restArgs = [3,5] Output: [1,2,3,4,5,6] Explanation: const partialFn = partial(fn, args) const result = partialFn(...restArgs) console.log(result) //Β [1,2,3,4,5,6] Placeholders "_" are replaced with values from the restArgs. Then the elements of theΒ argsΒ are passed as separate arguments to fn, which returns passed arguments as an array.
Example 3:
Input: fn = (a, b, c) => b + a - c, args = ["_", 5], restArgs = [5, 20] Output: -10 Explanation: const partialFn = partial(fn, args) const result = partialFn(...restArgs) console.log(result) //Β -10 Placeholder "_" is replaced with 5 and 20 is added at the end of args. Then the elements of theΒ argsΒ are passed as separate arguments to fn, which returns -10 (5 + 5 - 20).
Β
Constraints:
fnis a functionargsandrestArgsare valid JSON arrays1 <= args.length <= 5 * 1041 <=Β restArgs.length <= 5 * 1040 <= number of placeholders <= restArgs.length
Solutions
Solution 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |