Can someone please explain the purpose of double-negating the reverse
var in the below code?
return function (a,b) {
var A = key(a), B = key(b);
return ((A < B) ? -1 :
(A > B) ? +1 : 0)) * [-1,1][+!!reverse];
}
The way I understand it, the purpose is to pick the proper index from the [-1,1]
array to then use it in the multiplication but it seems to me that [-1,1][+!!reverse];
could be safely replaced by [-1,1][+reverse];
Am I wrong? What do you gain or prevent by double-negating reverse
there?
I saw the above code on this answer.
[-1] means the last element in a sequence, which in this is case is the list of tuples like (element, count) , order by count descending so the last element is the least common element in the original collection.
arr is a pointer to the first element of the array.So, if we move arr by 1 position it will point the second element. If the array base address is 1000, &arr+1 will be 1000 + (5 * 4) which is 1020. If the array base address is 1000, arr+1 will be 1000 + 4 which is 1004. Example.
The easiest answer is probably a counter-example:
+undefined //NaN
+!!undefined // 0
since contents of [] are generally converted to strings, [NaN] will attempt to access the property called "NaN" from the array, which does not exist and will return undefined:
[1,-1][+undefined]
[1,-1][NaN]
[1,-1]["NaN"]
undefined
Double negating simply ensures that we have a proper boolean. Since reverse could be anything, double negating it invokes JavaScript's "falsy" conversions. So, for example:
!!"hello" // true
!!"" // false
!!1 // true
!!some_undefined_var // false
The !!
converts the value to a boolean. This is needed if reverse
isn't a boolean to start off with.
Consider: +!!"hi"
. This is 1
, but +"hi"
is NaN
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With