i was messing around in the jquery Sizzle library framework and i saw this piece of code
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
a few question came up to mind :
- how to call this function
- what is the benefits to write this kind of function
- why it’s unique writing style?
- isn’t between the “sort” to the “function” not need to be “=” ?
besides the answers an article or tutorial about this stuff would be great.
At first I understood most of the code, but not all. The array shorthand and anonymous function were familiar to me, but I expect the sortFunction to take two arguments, where this one doesn’t take any. Because of this, I didn’t understand why you would do this: what the code hoped to accomplish.
Fortunately, a google search solved this for me. You can find the code on the jsPerf site, and view the original function from the question shown with context at this link:
http://jsperf.com/jquery-1-4-3-perf-degrade/4
Now we can also see the comments for the code:
If you’re familiar with how sort functions work, this now makes perfect sense. When sorting a sequence, the sort algorithm needs to frequently compare two items from the sequence, to know which one to sort ahead of the other. To allow you customize the sort, such functions will often allow you to pass another function as an argument, and it’s the job of this function to decide how the items compare with each other.
In this case, we have a small array that is already sorted. Any reasonable sort algorithm should call this function exactly once and then finish. However, a javascript compiler may try to optimize the compare function away in certain circumstances, so that it is not called. The purpose of this code, therefore, is to detect when that is happening. Before calling the function, you first set the
baseHasDuplicatevalue to true. Then you run this code, and aferwards check whether baseHasDuplicate has changed.