const partial = function (fn, ...partialArgs) {
let args = partialArgs.slice(0);
return function (...fullArguments) {
let arg = 0;
// Fill in the placeholders (undefined) with the provided arguments
for (let i = 0; i < args.length && arg < fullArguments.length; i++) {
if (args[i] === undefined) {
args[i] = fullArguments[arg++];
}
}
return fn.apply(this, args);
};
};
// Example 1: Fixing the timeout value in setTimeout (where time is the 2nd arg)
// setTimeout(callback, delay) -> we want to fix delay=10
const delayTenMsPartial = partial(setTimeout, undefined, 10);
delayTenMsPartial(() => console.log("Executed after 10ms"));
// Example 2: Creating a pretty-print JSON function
// JSON.stringify(value, replacer, space) -> fix replacer=null, space=2
const prettyPrintJson = partial(JSON.stringify, undefined, null, 2);
console.log(prettyPrintJson({ foo: "bar" }));