Skip to content

Latest commit

 

History

History
88 lines (66 loc) · 2.58 KB

File metadata and controls

88 lines (66 loc) · 2.58 KB

English Version

题目描述

现给定起始日期 start 、结束日期 end 和正整数 step ,返回一个生成器对象,该生成器对象按照从 startend(包括 start 和 end )的范围生成日期。所有日期都以字符串格式 YYYY-MM-DD 表示。step 的值表示连续生成的日期之间的天数间隔。

 

示例 1:

输入:start = "2023-04-01", end = "2023-04-04", step = 1
输出:["2023-04-01","2023-04-02","2023-04-03","2023-04-04"]
解释:
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'

示例 2:

输入:start = "2023-04-10", end = "2023-04-20", step = 3
输出:["2023-04-10","2023-04-13","2023-04-16","2023-04-19"]
解释:
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'

示例 3:

输入:start = "2023-04-10", end = "2023-04-10", step = 1
输出:["2023-04-10"]
解释:
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-10'

 

提示:

  • new Date(start) <= new Date(end)
  • 0 <= 结束日期与开始日期之间的天数差 <= 1000
  • 1 <= step <= 100

解法

方法一

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
 */