Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does same value zero algorithm works?

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.

like image 546
Johnny Depp Avatar asked May 18 '19 01:05

Johnny Depp


2 Answers

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:

  1. If Type(x) is different from Type(y), return false.
  2. 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.

  3. 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));
like image 80
CertainPerformance Avatar answered Sep 18 '22 23:09

CertainPerformance


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
like image 35
Alicia Avatar answered Sep 20 '22 23:09

Alicia