Skip to content

Instantly share code, notes, and snippets.

@gaearon
Last active July 8, 2024 06:18
Show Gist options
  • Save gaearon/08a85a33e3d08f3f2ca25fb17bd9d638 to your computer and use it in GitHub Desktop.
Save gaearon/08a85a33e3d08f3f2ca25fb17bd9d638 to your computer and use it in GitHub Desktop.
strictEquals.js
// Your scientists were so preoccupied
// with whether or not they could,
// they didn't stop to think if they should.
// Like a === b
function strictEquals(a, b) {
if (Object.is(a, b)) {
// Same value.
// Is this NaN?
if (Object.is(a, NaN)) { // We already know a and b are the same, so it's enough to check a.
// Special case #1.
return false;
} else {
// They are equal!
return true;
}
} else {
// Different value.
// Are these 0 and -0?
if (
(Object.is(a, 0) && Object.is(b, -0)) ||
(Object.is(a, -0) && Object.is(b, 0))
) {
// Special case #2.
return true;
} else {
// They are not equal!
return false;
}
}
}
@Saran-73
Copy link

Saran-73 commented Jul 5, 2024

const strictEquals = (a, b) => {
  const isSameValue = Object.is(a, b)
  // === behaves as same as Object.is() checks the both args are of same value or not
  // edge cases 
  // 0 === -0 || -0 === 0 // true
  // NaN === NaN // false 
  
  if(isSameValue && Object.is(a, NaN)){
      return false
   }
  if((Object.is(a , 0) && Object.is(b, -0)) || (Object.is(a, -0) && Object.is(b, 0))){
    return true
  }
  
 return isSameValue
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment