Finding next n leap years in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function that takes a positive integer n and returns an array of next n leap years. We will break this problem into three parts −

Part 1: Finding current year via JS

The code to find current year via JS will be −

// getting the current year from a new instance of Date object
const year = new Date().getFullYear();

Part 2: Checking for leap year

We will now write a function isLeap() that takes in a number and returns a boolean based on the number being a leap year or not.

A year is considered as a leap year if atleast one of these two conditions are met −

  • It is multiple of 400.
  • It is multiple of 4 and not multiple of 100.

Keeping these things in mind let’s write the function isLeap() −

// function to check for a leap year
const isLeap = year => {
   return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
};

Part 3: Finding next n leap years

Example

// function to check for a leap year
const isLeap = year => {
   return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
};
const nextNLeap = n => {
   const arr = [];
   let year = new Date().getFullYear()+1;
   while(arr.length < n){
      if(isLeap(year++)){
         arr.push(year-1);
      };
   };
   return arr;
};
console.log(nextNLeap(5));
console.log(nextNLeap(25));

Output

The output in the console will be −

[ 2024, 2028, 2032, 2036, 2040 ]
[
   2024, 2028, 2032, 2036, 2040,
   2044, 2048, 2052, 2056, 2060,
   2064, 2068, 2072, 2076, 2080,
   2084, 2088, 2092, 2096, 2104,
   2108, 2112, 2116, 2120, 2124
]
raja
Updated on 28-Aug-2020 14:08:06

Advertisements