Skip to content

Instantly share code, notes, and snippets.

@erineland
Last active April 26, 2019 15:41
Show Gist options
  • Save erineland/09de61da7c45447cbe947770382841f4 to your computer and use it in GitHub Desktop.
Save erineland/09de61da7c45447cbe947770382841f4 to your computer and use it in GitHub Desktop.
Object.is() polyfill - A small coding exercise to use JavaScript types and coercion to write my own Object.is().
// TODO: define polyfill for `Object.is(..)`
if (!Object.is || true) {
Object.is = function(firstValue, secondValue) {
// Take NaN into account
if (typeof(firstValue) === 'number' && typeof(secondValue) === 'number') {
if (firstValue.toString() === 'NaN' && secondValue.toString() === 'NaN') {
return firstValue.toString() === 'NaN' && secondValue.toString() === 'NaN'
}
}
// Take -0 into account - 1/-0 is -Infinity, 1/0 is Infinity.
if (firstValue === 0 || secondValue === 0) {
return (1 / firstValue) === (1 / secondValue);
}
// Otherwiser test using ===
return firstValue === secondValue;
}
}
// tests:
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