The code that I am practicing with is where I have a function called InReverse. This function accepts a function as an argument and returns a function. When the function returned is invoked, it reverses the order of the arguments.
When the returned functions are returned:
const catDog = ('cat', 'dog') => returns ('dog cat')
What I have rewritten out so far is:
function inReverse (func) {
return function (...arguments) {
return arguments.map((element) => {
element.reverse();
});
}
}
Any guidance would be appreciated!
CodePudding user response:
You need to simply call the input function inside the newly created anonymous function.
For example this works:
function inReverse(f) {
return function () {
let args = [...arguments].reverse();
return f.apply(this, args);
}
}
So for example if you have subtract
function like this:
function subtract(a, b) {
return a-b;
}
subtract(1, 10);
will be -9 as expected.
and inReverse(subtract)(1, 10)
will be 9 as expected.
CodePudding user response:
Not sure why you're using map
, just call reverse
right on the arguments
array. Also you weren't calling func
:
function inReverse(func) {
return function(...args) {
return func(...args.reverse());
};
}
(Notice that arguments
is a reserved identifier in strict mode, you should name your parameter for something else)
CodePudding user response:
Just reverse the arguments, and use func.apply(this, arr)
function inReverse(func) {
return function() {
var args = Array.prototype.slice.call(arguments)
args = args.reverse();
return func.apply(this, args);
}
}
function div(a, b) {
return a / b
}
console.log(div(1, 2))
console.log(inReverse(div)(1, 2))
CodePudding user response:
Not sure, why you are using map method, just use reverse method in your function right on the arguments. Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse?retiredLocale=id