A utility to check if a given year is a leap year
npm install leap-year-checkerReturns true if the value is leap year. A simple JavaScript function to check if a given year is a leap year. This function includes error handling to validate the input.
``bash`
npm install leap-year-checker
`python
const { isLeapYear, getLeapYears, getNextLeapYear, getPreviousLeapYear } = require("leap-year-checker");
try {
// Check if a year is a leap year
console.log(isLeapYear(2024)); // Expected output: true
console.log(isLeapYear(2023)); // Expected output: false
// Find leap years within a range
console.log(getLeapYears(2000, 2024)); // Expected output: [2000, 2004, 2008, 2012, 2016, 2020, 2024]
// Get the next leap year after a given year
console.log(getNextLeapYear(2023)); // Expected output: 2024
// Get the previous leap year before a given year
console.log(getPreviousLeapYear(2024)); // Expected output: 2020
// Error handling for invalid inputs
console.log(isLeapYear("2024")); // Throws error: Invalid input: year must be a positive integer.
} catch (error) {
console.error("Error:", error.message);
}
``Function Implementation
python
/**
* Checks if a provided year is a leap year.
* @param {number} year - The year to check
* @throws {Error} - Throws an error if the input is not a valid positive integer
* @returns {boolean} - Returns true if the year is a leap year, false otherwise
*/
function isLeapYear(year) {
// Error handling: Check if input is a valid number and an integer
if (typeof year !== 'number' || !Number.isInteger(year) || year <= 0) {
throw new Error("Invalid input: year must be a positive integer.");
}
// Return true if it's a leap year, false otherwise
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
``
Pull requests are welcome. For major changes, please open an issue first
to discuss what you would like to change.
Please make sure to update tests as appropriate.
This project is licensed under the MIT License.