Skip to content

Commit 6f7352f

Browse files
feat: add check leap year algorithm
1 parent 5c39e87 commit 6f7352f

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎Maths/CheckLeapYear.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @function checkLeapYear
3+
* @description A leap year is a year that is divisible by 4, except for
4+
* century years which must be divisible by 400. This function checks
5+
* whether a given year is a leap year.
6+
* @param {number} year - A positive integer representing a year
7+
* @returns {boolean} - True if the year is a leap year, false otherwise
8+
* @see https://en.wikipedia.org/wiki/Leap_year
9+
* @example checkLeapYear(2000) => true
10+
* @example checkLeapYear(1900) => false
11+
* @example checkLeapYear(2024) => true
12+
*/
13+
const checkLeapYear = (year) => {
14+
if (!Number.isInteger(year) || year < 1) {
15+
throw new TypeError('Input must be a positive integer')
16+
}
17+
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
18+
}
19+
20+
export { checkLeapYear }

‎Maths/test/CheckLeapYear.test.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { checkLeapYear } from '../CheckLeapYear.js'
2+
3+
describe('checkLeapYear', () => {
4+
test('2000 is a leap year', () => {
5+
expect(checkLeapYear(2000)).toBe(true)
6+
})
7+
8+
test('1900 is NOT a leap year', () => {
9+
expect(checkLeapYear(1900)).toBe(false)
10+
})
11+
12+
test('2024 is a leap year', () => {
13+
expect(checkLeapYear(2024)).toBe(true)
14+
})
15+
16+
test('2023 is NOT a leap year', () => {
17+
expect(checkLeapYear(2023)).toBe(false)
18+
})
19+
20+
test('1600 is a leap year', () => {
21+
expect(checkLeapYear(1600)).toBe(true)
22+
})
23+
24+
test('1700 is NOT a leap year', () => {
25+
expect(checkLeapYear(1700)).toBe(false)
26+
})
27+
28+
test('2100 is NOT a leap year', () => {
29+
expect(checkLeapYear(2100)).toBe(false)
30+
})
31+
32+
test('400 is a leap year', () => {
33+
expect(checkLeapYear(400)).toBe(true)
34+
})
35+
36+
test('throws TypeError for zero', () => {
37+
expect(() => checkLeapYear(0)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for negative input', () => {
41+
expect(() => checkLeapYear(-4)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for float input', () => {
45+
expect(() => checkLeapYear(2024.5)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)