#javascript
Вопрос:
Они partialLeft
и partialRight
функции содержат одни и те же вещи в теле, но они принимают разные возвращаемые значения.
Почему возникла такая ситуация?
function partialLeft(f, ...outerArgs) {
return function(...innerArgs) { // Return this function
let args = [...outerArgs, ...innerArgs]; // Build the argument list
return f.apply(this, args); // Then invoke f with it
};
}
// The arguments to this function are passed on the right
function partialRight(f, ...outerArgs) {
return function(...innerArgs) { // Return this function
let args = [...innerArgs, ...outerArgs]; // Build the argument list
return f.apply(this, args); // Then invoke f with it
};
}
// The arguments to this function serve as a template. Undefined values
// in the argument list are filled in with values from the inner set.
function partial(f, ...outerArgs) {
return function(...innerArgs) {
let args = [...outerArgs]; // local copy of outerargs template
let innerIndex=0; // which inner arg is next
// Loop through the args, filling in undefined values from inner args
for(let i = 0; i < args.length; i ) {
if (args[i] === undefined) args[i] = innerArgs[innerIndex ];
}
// Now append any remaining inner arguments
args.push(...innerArgs.slice(innerIndex));
return f.apply(this, args);
};
}
// Here is a function with three arguments
const f = function(x,y,z) { return x * (y - z); };
// Notice how these three partial applications differ
partialLeft(f, 2)(3,4) // => -2: Bind first argument:
2 * (3 - 4)
partialRight(f, 2)(3,4) // => 6: Bind last argument:
3 * (4 - 2)
partial(f, undefined, 2)(3,4) // => -6: Bind middle argument: 3 * (2 - 4)
Ответ №1:
эти функции partialeft и partialRight содержат в теле одно и то же
Нет, это не так. Сначала делает
let args = [...outerArgs, ...innerArgs];
Второй делает
let args = [...innerArgs, ...outerArgs];
таким образом, их порядок меняется на противоположный.