Even Or Odd

·

2 min read

Description

I recently completed a coding challenge on CodeWars called "Even Or Odd." The challenge was to create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. It's a simple problem but can be useful in various scenarios.

Problem Solving Approach

To solve the problem, I followed these steps:

  1. Read and understand the problem: I carefully read the problem statement and made sure I understood what was being asked. Additionally, I considered potential edge cases such as odd numbers, no input being passed, and incorrect data types.

  2. Plan and design: I devised a plan or algorithm to solve the problem. In this case, I used the modulus operator in conjunction with a ternary statement to return either "Even" or "Odd". If the given number is divisible by 2 (i.e., the remainder is 0), I return "Even", otherwise, I return "Odd".

Implementation

Here's the code snippet for the evenOrOdd function:

/*
 * Checks whether the given number is Even or Odd.
 * @param number - Integer number
 * @returns "Even" if the number is even, "Odd" otherwise.
 */
function evenOrOdd(number) {
  if (isNaN(number)) return;

  return number % 2 == 0 ? "Even" : "Odd";
}

Unit Testing

I also wrote unit tests using Jest to verify the correctness of the evenOrOdd function. Here are some example test cases:

// Import the function
const evenOrOdd = require('./EvenOrOdd');

// Test cases
describe('evenOrOdd', () => {
  it('should return "Even" for even numbers', () => {
    expect(evenOrOdd(2)).toBe('Even');
    expect(evenOrOdd(0)).toBe('Even');
    expect(evenOrOdd(-4)).toBe('Even');
    expect(evenOrOdd(100)).toBe('Even');
  });

  it('should return "Odd" for odd numbers', () => {
    expect(evenOrOdd(1)).toBe('Odd');
    expect(evenOrOdd(7)).toBe('Odd');
    expect(evenOrOdd(-3)).toBe('Odd');
    expect(evenOrOdd(99)).toBe('Odd');
  });

  it('should return undefined for non-numeric values', () => {
    expect(evenOrOdd('hello')).toBeUndefined();
    expect(evenOrOdd(NaN)).toBeUndefined();
    expect(evenOrOdd(null)).toBeUndefined();
    expect(evenOrOdd(undefined)).toBeUndefined();
  });
});

These tests cover various scenarios including even numbers, odd numbers, and non-numeric values.

I hope this post gives you an insight into solving the "Even Or Odd" coding challenge and the importance of unit testing. Feel free to explore the complete code on my GitHub repository and try it out yourself!