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.
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.
Share Improve this question asked May 18, 2019 at 1:54 Johnny DeppJohnny Depp 1711 silver badge6 bronze badges 3- 2 Does this help at all? – Alicia Sykes Commented May 18, 2019 at 2:02
- Yeah ! great article thnx :) – Johnny Depp Commented May 18, 2019 at 3:10
- 1 Accept one of your answers, if either of them solved your problem- you will get +2 rep. – Alicia Sykes Commented May 18, 2019 at 3:48
2 Answers
Reset to default 18See 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:
- Same value zero considers that NaN is equal with NaN
- Strict equality considers that NaN is not equal with NaN