Skip to main content
Back to problems
#2777
Medium JavaScript

Date range generator

82.7% acceptance
Mar 31, 2026
11
2
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.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
function* dateRangeGenerator(
  start: string,
  end: string,
  step: number,
): Generator<string> {
  let current = new Date(start);
  const endDate = new Date(end);
  while (current <= endDate) {
  yield current.toISOString().slice(0, 10);
  current.setDate(current.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
 */