Skip to content

2777. Date Range Generator πŸ”’

Description

Given a start date start, an end date end, and a positive integerΒ step, return a generator object that yieldsΒ dates in the range from start to endΒ inclusive.

The value ofΒ stepΒ indicates the number of days between consecutive yielded values.

All yielded datesΒ must be in the string formatΒ YYYY-MM-DD.

Β 

Example 1:

Input: start = "2023-04-01", end = "2023-04-04", step = 1
Output: ["2023-04-01","2023-04-02","2023-04-03","2023-04-04"]
Explanation: 
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-01'
g.next().value // '2023-04-02'
g.next().value // '2023-04-03'
g.next().value // '2023-04-04'

Example 2:

Input: start = "2023-04-10", end = "2023-04-20", step = 3
Output: ["2023-04-10","2023-04-13","2023-04-16","2023-04-19"]
Explanation: 
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-10'
g.next().value // '2023-04-13'
g.next().value // '2023-04-16'
g.next().value // '2023-04-19'

Example 3:

Input: start = "2023-04-10", end = "2023-04-10", step = 1
Output: ["2023-04-10"]
Explanation: 
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-10'

Β 

Constraints:

  • new Date(start) <= new Date(end)
  • start and end datesΒ are in the string formatΒ YYYY-MM-DD
  • 0 <= The difference in days between the start date and the end date <= 1500
  • 1 <= step <= 1000

Solutions

Solution 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
function* dateRangeGenerator(start: string, end: string, step: number): Generator<string> {
    const startDate = new Date(start);
    const endDate = new Date(end);
    let currentDate = startDate;
    while (currentDate <= endDate) {
        yield currentDate.toISOString().slice(0, 10);
        currentDate.setDate(currentDate.getDate() + step);
    }
}

/**
 * const g = dateRangeGenerator('2023-04-01', '2023-04-04', 1);
 * g.next().value; // '2023-04-01'
 * g.next().value; // '2023-04-02'
 * g.next().value; // '2023-04-03'
 * g.next().value; // '2023-04-04'
 * g.next().done; // true
 */

Comments