Home > Enterprise >  How to short the expression?
How to short the expression?

Time:09-30

I have that expression

if (a === Infinity && b === 0 || a === -Infinity && b === 0 || a === 0 && b === Infinity || a === 0 && b === -Infinity) {
        return NaN
    }

I want short it, but I have no idea how to do this

CodePudding user response:

You can use !isFinite() to test if it's either Infinity or -Infinity.

if ((!isFinite(a) && b === 0) || (!isFinite(b) && a === 0)) {
    return NaN;
}

CodePudding user response:

Math.absing both and then checking that the minimum is 0 and the maximum is infinity should do it.

const nums = [a, b].map(Math.abs);
if (Math.min(...nums) === 0 && Math.max(...nums) === Infinity) {
  return NaN;
}

Can also sort the array.

const nums = [a, b]
  .map(Math.abs)
  .sort(a, b) => a - b); // .sort() works too, but could be more confusing
if (nums[0] === 0 && nums[1] === Infinity)) {
  return NaN;
}
  • Related