Shortest function that gives same result as === when comparing 2 variables

67 Views Asked by At

This is my take on it. Is it possible to make it shorter? (Not just by turning it into an arrow function) Must not use any ===

this is my third attempt, I really don't know now if its possible to shorten it evem further

function strictEquals(a, b) {
  if ([a, b].every(isNaN)) return false;
  return Object.is(a + 0, b + 0) || Object.is(a, b);
}

second attempt.

function strictEquals(a, b) {
  if (Number.isNaN(a) && Number.isNaN(b)) {
    return false;
  }
  if (
    (Object.is(a, 0) && Object.is(b, -0)) ||
    (Object.is(a, -0) && Object.is(b, 0))
  ) {
    return true;
  }
  return Object.is(a, b);
}

you can test yours with this battery of tests

console.log('(1, 1), expected true', strictEquals(1, 1));
console.log('(NaN, NaN), expected false', strictEquals(NaN, NaN));
console.log('(0, -0), expected true', strictEquals(0, -0));
console.log('(-0, 0), expected true', strictEquals(-0, 0));
console.log("(1, '1'),expected false", strictEquals(1, '1'));
console.log('(true, false), expected false',strictEquals(true,false));
console.log('(false, false), expected true', strictEquals(false,false));
console.log("('Water', 'Oil'), expected false", strictEquals('Water', 'Oil'));
console.log('(Undefined, NaN), expected false', strictEquals(undefined, NaN));

this one was a mistake (my first attempt)

function strictEquals(a, b) { if ((Number.isNaN(a) && Number.isNaN(b)) || !Object.is(a, b)) return false; return Object.is(a + 1, b + 1); }
1

There are 1 best solutions below

3
Roman Kurbatov On

Modified version:

function strictEqual(a,b) {
  return (Object.is(a, b) || Object.is(a+1, b+1)) && !Number.isNaN(a)
}