This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
116. implement Object.is()
Sure, here's an implementation of Object.is()
:
function is(x, y) {
if (x === y) {
// Handle +0 == -0
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
// Handle NaN == NaN
return x !== x && y !== y;
}
}
The function first checks if x
and y
are strictly equal (===
) and returns true
if so. However, it also checks for two special cases: if x
and y
are both 0, it returns false
if one is positive and the other is negative. This correctly handles the fact that JavaScript distinguishes between positive and negative zero. If x
and y
are not strictly equal, the function returns true
if both are NaN
. This ensures that NaN
is considered equal to itself, as required by the spec.