formatSeconds
const formatSeconds = s => {
const [hour, minute, second, sign] =
s > 0
? [s / 3600, (s / 60) % 60, s % 60, '']
: [-s / 3600, (-s / 60) % 60, -s % 60, '-'];
return (
sign +
[hour, minute, second]
.map(v => `${Math.floor(v)}`.padStart(2, '0'))
.join(':')
);
};
formatSeconds(200); // '00:03:20'
formatSeconds(-200); // '-00:03:20'
formatSeconds(99999); // '27:46:39'
rangeGenerator
const rangeGenerator = (end, start = 0, step = 1) => {
function* generateRange() {
let x = start - step;
while(x < end - step) yield x += step;
}
return {
[Symbol.iterator]: generateRange
};
}
console.log([...rangeGenerator(7)]); // [0, 1, 2, 3, 4, 5, 6]
for (let i of rangeGenerator(8, 2, 2)) console.log(i); // Logs: 2, 4, 6
dateRangeGenerator
const dateRangeGenerator = function* (start, end, step = 1) {
let d = start;
while (d < end) {
yield new Date(d);
d.setDate(d.getDate() + step);
}
};
[...dateRangeGenerator(new Date('2021-06-01'), new Date('2021-06-04'))];
// [ 2021-06-01, 2021-06-02, 2021-06-03 ]