I was going through map chapter in Javascript.info and there is a link given to SameValueZero algorithm. Can someone explain how does that algorithm works in simple words.
I tried going through the link but can't find anything.
See the specification:
The internal comparison abstract operation SameValueZero(x, y), where x and y are ECMAScript language values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
If Type(x) is Number, then
If x is NaN and y is NaN, return true.
If x is +0 and y is -0, return true.
If x is -0 and y is +0, return true.
If x is the same Number value as y, return true.
Return false.
Return SameValueNonNumber(x, y).
It's basically the same as a ===
test, except that when x
and y
are both NaN
, they pass the test as well. You could implement it like this:
const sameValueZero = (x, y) => x === y || (Number.isNaN(x) && Number.isNaN(y));
console.log(sameValueZero(0, 0));
console.log(sameValueZero(0, 1));
console.log(sameValueZero(0, NaN));
console.log(sameValueZero(NaN, NaN));
Same value zero comparison algorithm (see here why), which is a modified version of the strict equality comparison. The main difference between the two is NaN with NaN equality consideration:
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