上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {string} start
* @param {string} end
* @param {number} step
* @yields {string}
*/
var dateRangeGenerator = function* (start, end, 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
*/
javascript 解法, 执行用时: 76 ms, 内存消耗: 43.6 MB, 提交时间: 2023-10-15 14:43:10
/**
* @param {string} start
* @param {string} end
* @param {number} step
* @yields {string}
*/
var dateRangeGenerator = function* (start, end, step) {
var startDate = new Date(start), endDate = new Date(end);
for (var date = startDate; date <= endDate; date.setDate(date.getDate() + step)) {
yield date.toISOString().slice(0, 10);
}
};
/**
* 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
*/
javascript 解法, 执行用时: 76 ms, 内存消耗: 43.5 MB, 提交时间: 2023-10-15 14:42:53
/**
* @param {string} start
* @param {string} end
* @param {number} step
* @yields {string}
*/
var dateRangeGenerator = function* (start, end, step) {
const i = Math.floor((new Date(end) - new Date(start)) / 24 / 3600 / 1000 / step)
var j = 1
while (j <= i + 1) {
yield (new Date(new Date(start).getTime() + step * (j - 1) * 24 * 3600 * 1000)).toISOString().slice(0, 10)
j++
}
};
/**
* 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
*/
typescript 解法, 执行用时: 88 ms, 内存消耗: 46.9 MB, 提交时间: 2023-10-15 14:42:33
// 格式化日期
function format(timestamp: number): string {
const date = _Date(timestamp);
const month = date.getMonth() + 1
const day = date.getDate()
return `${date.getFullYear()}-${month < 10 ? `0${month}` : month}-${day < 10 ? `0${day}` : day}`
}
function _Date(ts: number | string): Date {
return new Date(ts);
}
function* dateRangeGenerator(start: string, end: string, step: number): Generator<string> {
const startTime = _Date(start).getTime();
const endTime = _Date(end).getTime();
// 计算日期相差天数
const diffDays = ~~((endTime - startTime) / (1000 * 3600 * 24));
// 说明开始和结束日期相同
if (!diffDays) {
yield format(startTime);
return;
}
let i = 0, curDay = Number(start.slice(8));
while (i <= diffDays) {
// 跳转日期并格式化输出
yield format(_Date(start).setDate(curDay));
// 记录跳转位置
i += step;
// 从初始开始日期不断往后加步数
curDay += 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
*/