Home > katas > Even or Odd (8kyu) [TypeScript]

Even or Odd (8kyu) [TypeScript]


This is a very popular kata. Let's solve it!

Chek kata on Codewars

Description:

Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.

Let's use Remainder (%) operator. It returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

4 % 2 // 0
3 % 2 // 1

If the number is even it returns 0 and if the number is odd it returns 1. Which converts to false or true accordingly.

export const even_or_odd = (n: number): String => (n % 2 === 0) ? 'Even' : 'Odd'

Let's check others solutions.

Some people prefer to use the bitwise AND operator insted. Basicly solution is the same.

export function even_or_odd(n:number):String {
  return n & 1 ? "Odd" : "Even";
}

Math.abs() is another flavor of the same idea.

export function even_or_odd(n:number):String {
  return (Math.abs(n % 2) == 0) ? "Even" : "Odd";
}

Alternatively, we can create an array with 'Even' and 'Odd' values and return the first or second element.

export function even_or_odd(n:number):String {
  return ['Even', 'Odd'][n % 2];
}
© 2021, Andrew Losseff