mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Added jest file in tests, added description and normal even number test(divisibility by 2 )
This commit is contained in:
@ -1,4 +1,5 @@
|
||||
/* Even Number: https://simple.wikipedia.org/wiki/Even_number
|
||||
/*
|
||||
* Even Number: https://simple.wikipedia.org/wiki/Even_number
|
||||
*
|
||||
* function to check if number is even
|
||||
* return true if number is even
|
||||
@ -10,10 +11,46 @@
|
||||
* @return {boolean}
|
||||
*/
|
||||
|
||||
const isEven = (number) => {
|
||||
return (number & 1) === 0
|
||||
/*
|
||||
* Checking if number is even using divisibility by 2
|
||||
*
|
||||
* If number is divisible by 2 i.e remainder = 0, then it is even
|
||||
* therefore, the function will return true
|
||||
*
|
||||
* If number is not divisible by 2 i.e remainder != 0, then it is not even i.e odd
|
||||
* therefore, the function will return false
|
||||
*/
|
||||
|
||||
export const isEven = (number) => {
|
||||
return number % 2 === 0
|
||||
}
|
||||
|
||||
// testing
|
||||
console.log(isEven(4))
|
||||
console.log(isEven(7))
|
||||
/*
|
||||
* Checking if number is even using bitwise operator
|
||||
*
|
||||
* Bitwise AND (&) compares the bits of the 32
|
||||
* bit binary representations of the number and
|
||||
* returns a number after comparing each bit:
|
||||
*
|
||||
* 0 & 0 -> 0
|
||||
* 0 & 1 -> 0
|
||||
* 1 & 0 -> 0
|
||||
* 1 & 1 -> 1
|
||||
*
|
||||
* For odd numbers, the last binary bit will be 1
|
||||
* and for even numbers, the last binary bit will
|
||||
* be 0.
|
||||
*
|
||||
* As the number is compared with one, all the
|
||||
* other bits except the last will become 0. The
|
||||
* last bit will be 0 for even numbers and 1 for
|
||||
* odd numbers, which is checked with the use
|
||||
* of the equality operator.
|
||||
*
|
||||
* References:
|
||||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND
|
||||
*/
|
||||
|
||||
export const isEvenBitwise = (number) => {
|
||||
return (number & 1) === 0
|
||||
}
|
||||
|
21
Maths/test/IsEven.test.js
Normal file
21
Maths/test/IsEven.test.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { isEven, isEvenBitwise } from '../IsEven'
|
||||
|
||||
test('should return if the number is even or not', () => {
|
||||
const isEvenNumber = isEven(4)
|
||||
expect(isEvenNumber).toBe(true)
|
||||
})
|
||||
|
||||
test('should return if the number is even or not', () => {
|
||||
const isEvenNumber = isEven(7)
|
||||
expect(isEvenNumber).toBe(false)
|
||||
})
|
||||
|
||||
test('should return if the number is even or not', () => {
|
||||
const isEvenNumber = isEvenBitwise(6)
|
||||
expect(isEvenNumber).toBe(true)
|
||||
})
|
||||
|
||||
test('should return if the number is even or not', () => {
|
||||
const isEvenNumber = isEvenBitwise(3)
|
||||
expect(isEvenNumber).toBe(false)
|
||||
})
|
Reference in New Issue
Block a user