O
O
olya_0972018-01-31 02:55:36
JavaScript
olya_097, 2018-01-31 02:55:36

Please explain the code in JS (comments, if possible). Particularly interested in why is this here?

Write a function applyAll(func, arg1, arg2...) that takes a function func and an arbitrary number of arguments.
It should call func(arg1, arg2...), that is, pass all arguments to func, starting with the second one, and return the result.
function sum() {
return [].reduce.call(arguments, function(a, b) {
return a + b;
});
}
function mul() {
return [].reduce.call(arguments, function(a, b) {
return a * b;
});
}
function applyAll(func) {
return func.apply(this, [].slice.call(arguments, 1));
}
alert( applyAll(sum, 1, 2, 3) ); // 6
alert( applyAll(mul, 2, 3, 4) ); // 24
alert( applyAll(Math.max, 2, -2, 3) ); // 3
alert( applyAll(Math.min, 2, -2, 3) ); // -2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xmoonlight, 2018-01-31
@xmoonlight

https://learn.javascript.ru/call-apply
I advise you to study the entire section "Object methods and call context".

A
amokrushin, 2018-01-31
@amokrushin

this is not needed in this example, you can replace it with anything null, 1, NaN, undefined...
Otherwise, this code considers crutches around arguments rather than using a call context.
The only thing you need to know about "arguments" now is never to use it.
In modern js, this code might look something like this:

function sum(...args) {
  return args.reduce((acc, val) => acc + val);
}

function mul(...args) {
  return args.reduce((acc, val) => acc * val);
}

function applyAll(func, ...values) {
  return func(...values);
}

alert( applyAll(sum, 1, 2, 3) ); // 6
alert( applyAll(mul, 2, 3, 4) ); // 24
alert( applyAll(Math.max, 2, -2, 3) ); // 3
alert( applyAll(Math.min, 2, -2, 3) ); // -2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question