is-even icon indicating copy to clipboard operation
is-even copied to clipboard

a better solution

Open lovetingyuan opened this issue 3 years ago • 5 comments

module.exports = function iseven(n) {
  return n % 2 == 0
}

image

lovetingyuan avatar Aug 19 '21 10:08 lovetingyuan

The one thing his does that the above does not do is ... that the number could be typed out. Below might be another possibility.

sEven = (value) => {
  if (isNaN(+value)) {
    return !!value.match(/(?:zero|two|four|six|eight|ten|twelve|fourteen|sixteen|eighteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|billion)$/gi);
  } else {
    return +value % 2 === 0;
  }
}

tmburnell avatar Aug 19 '21 12:08 tmburnell

Ew, modulo. If you're going for the better solution use bitwise.

module.exports = function IsEven(n) {
  return !(n & 1)
}

northmatt avatar Aug 20 '21 03:08 northmatt

Bitwise op cannot be used, for example:

isEven(2.2) // true

kyriosli avatar Aug 20 '21 03:08 kyriosli

Bitwise op cannot be used, for example:

Nor can modulo operator be used on floats without doing a bunch of extra steps. Dividing 2.2 by two leaves you with 1.1, which is one with a remainder of some sorts.

Not to mention, it seems the general online consensus is that one cannot have an even/odd decimal value. For example 2.3 by our standard rules would be odd, but 2.30 by the standard rules would be even (is the last digit even/odd?). Or whether 2/3 is even/odd (2.66666, last number technically doesnt exist which is undefined, is six which is even, is rounded to 2.67 which is odd if you ignore the fact you can add trailing zeros to make it even, or thought about logically as a fraction which is probably odd). Im not a math expert so who knows how correct that is.

northmatt avatar Aug 20 '21 04:08 northmatt

Arithmetic operations on BigInt and Number will trhow a TypeError.

2n % 2 // Uncaught TypeError: can't convert BigInt to number

tuchida avatar Aug 21 '21 00:08 tuchida