Last active
September 22, 2019 01:42
-
-
Save lucifiel0121/69e8eee4e16dbdbe543663656faf8028 to your computer and use it in GitHub Desktop.
implementation Object.is (js)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (!Object.is || true) { | |
Object.is = function ObjectIs(x,y) { | |
var xNegZero = isItNegZero(x); | |
var yNegZero = isItNegZero(y); | |
/* 先過濾 -0 */ | |
if (xNegZero || yNegZero) { | |
return xNegZero && yNegZero; | |
} | |
/* 再過濾 NaN */ | |
else if (isItNaN(x) && isItNaN(y)) { | |
return true; | |
} | |
/* 排除 corner case 再回來用嚴格相等(===) */ | |
else if (x === y) { | |
return true; | |
} | |
return false; | |
// ********** | |
/** | |
* @description -0 | |
* @condition value === 0 | |
* @condition 1 / num : 利用可以區分正負的特性,嚴格等於對 NegZero (===) 無效 | |
* 1/0 = (+)Infinity , 1/-0 = -Infinity | |
*/ | |
function isItNegZero(num) { | |
return num === 0 && (1 / num) === -Infinity; | |
} | |
/** | |
* @description 有人會先判斷是不是數字,在判斷是不是 isNaN | |
* @example 這邊直接用 IEEE 754 定義 (NaN ≠ x) = false,一樣可以簡易判斷,全 js 只有 NaN 這個特殊值符合條件 | |
* */ | |
function isItNaN(self) { | |
return self !== self; | |
} | |
}; | |
} | |
// tests: 以下都要為 true | |
console.log(Object.is(42,42) === true); | |
console.log(Object.is("foo","foo") === true); | |
console.log(Object.is(false,false) === true); | |
console.log(Object.is(null,null) === true); | |
console.log(Object.is(undefined,undefined) === true); | |
console.log(Object.is(NaN,NaN) === true); | |
console.log(Object.is(-0,-0) === true); | |
console.log(Object.is(0,0) === true); | |
console.log(Object.is(-0,0) === false); | |
console.log(Object.is(0,-0) === false); | |
console.log(Object.is(0,NaN) === false); | |
console.log(Object.is(NaN,0) === false); | |
console.log(Object.is(42,"42") === false); | |
console.log(Object.is("42",42) === false); | |
console.log(Object.is("foo","bar") === false); | |
console.log(Object.is(false,true) === false); | |
console.log(Object.is(null,undefined) === false); | |
console.log(Object.is(undefined,null) === false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment