Create dateRangeGenerator.md

This commit is contained in:
Isabelle Viktoria Maciohsek
2021-06-20 12:39:16 +03:00
committed by GitHub
parent 0f48b6bf9c
commit d27c9e5590

View File

@ -0,0 +1,26 @@
---
title: dateRangeGenerator
tags: date,function,generator,advanced
firstSeen: 2021-06-21T05:00:00-04:00
---
Creates a generator, that generates all dates in the given range using the given step.
- Use a `while` loop to iterate from `start` to `end`, using `yield` to return each date in the range, using the `Date` constructor.
- Use `Date.prototype.getDate()` and `Date.prototype.setDate()` to increment by `step` days after returning each subsequent value.
- Omit the third argument, `step`, to use a default value of `1`.
```js
const dateRangeGenerator = function* (start, end, step = 1) {
let d = start;
while (d < end) {
yield new Date(d);
d.setDate(d.getDate() + step);
}
};
```
```js
[...dateRangeGenerator(new Date('2021-06-01'), new Date('2021-06-04'))];
// [ 2021-06-01, 2021-06-02, 2021-06-03 ]
```