'What is this function doing calling itself from within?
Below given function is JS sorting function based on multiple criteria. I found this cool function on some website. It would be great if someone could explain this function to me.
I am unable to understand the last part of it, where it is calling itself with another parentheses given a & b variables inside it. sortbyMultipleKeys(keys.slice(1))(a, b)
calling a function this way; totally new to me f()(a,b) <-- Howwwwwwwwwww??? :|.
I would highly appreciate if anyone could explain it with some examples. :)
var obj = [
{alpha: 'c',year: 2002},
{alpha: 'b',year: 2004},
{alpha: 'a',year: 2004},
{alpha: 'd',year: 2003},
{alpha: 'a',year: 2002},
{alpha: 'c',year: 2004},
{alpha: 'd',year: 2001},
{alpha: 'b',year: 2002},
{alpha: 'a',year: 2003},
{alpha: 'b',year: 2002},
{alpha: 'd',year: 2001},
{alpha: 'c',year: 2004}
];
function sortbyMultipleKeys(keys) {
return function(a, b) {
if (keys.length == 0) return;
key = keys[0];
if (a[key] > b[key]) return 1;
else if (a[key] < b[key]) return -1;
else return sortbyMultipleKeys(keys.slice(1))(a, b);
}
}
let a = obj.sort(sortbyMultipleKeys(["alpha", "year"]));
console.log(a)
Solution 1:[1]
What's special about JavaScript, is the fact that you can return a function from a function.
function foo(){
return function() { console.log('Hello!'); }
}
console.log(foo()); //prints function bar () { console.log('Hello') }
foo()(); //prints Hello!
So what sortbyMultipleKeys(keys.slice(1))(a, b)
is essentially doing, is calling a function that was returned from the sortbyMultipleKeys
function.
function sortbyMultipleKeys(keys) {
return function(a, b) { //notice how this function is being returned
if (keys.length == ...
}
}
If you don't understand how sortbyMultipleKeys
works, I suggest to read about 'closures'.
For example, when you do
console.log(sortbyMultipleKeys(["alpha", "year"]))
you'll see that a function is printed.
/* prints: ƒ (a, b) {
if (keys.length == 0) return;
key = keys[0];
if (a[key] > b[key]) return 1;
else if (a[key] < b[key]) return -1;
else return sortbyMultipleKeys(keys.slice(1))(a, b);
} */
Notice that keys
variable exists in the function even though it is only accessible in the sortbyMultipleKeys
scope. But this runs perfectly thanks to closures. And it's probably the most essential part of this code.
Solution 2:[2]
This is a function:
hi = (s) => "hi from " + s
this lets us define:
() => hi('a')
what happens when we do this?
(() => hi('a'))()
or this:
(() => hi)()('a')
They all output the same thing? A function is just a thing. JavaScript lets you return things. The method invocation operator ()
invokes functions. It lets you retrieve what's inside of them.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | halfer |
Solution 2 | Paul Nikonowicz |