formatSeconds

  1. const formatSeconds = s => {
  2. const [hour, minute, second, sign] =
  3. s > 0
  4. ? [s / 3600, (s / 60) % 60, s % 60, '']
  5. : [-s / 3600, (-s / 60) % 60, -s % 60, '-'];
  6. return (
  7. sign +
  8. [hour, minute, second]
  9. .map(v => `${Math.floor(v)}`.padStart(2, '0'))
  10. .join(':')
  11. );
  12. };
  13. formatSeconds(200); // '00:03:20'
  14. formatSeconds(-200); // '-00:03:20'
  15. formatSeconds(99999); // '27:46:39'

rangeGenerator

  1. const rangeGenerator = (end, start = 0, step = 1) => {
  2. function* generateRange() {
  3. let x = start - step;
  4. while(x < end - step) yield x += step;
  5. }
  6. return {
  7. [Symbol.iterator]: generateRange
  8. };
  9. }
  10. console.log([...rangeGenerator(7)]); // [0, 1, 2, 3, 4, 5, 6]
  11. for (let i of rangeGenerator(8, 2, 2)) console.log(i); // Logs: 2, 4, 6

dateRangeGenerator

  1. const dateRangeGenerator = function* (start, end, step = 1) {
  2. let d = start;
  3. while (d < end) {
  4. yield new Date(d);
  5. d.setDate(d.getDate() + step);
  6. }
  7. };
  8. [...dateRangeGenerator(new Date('2021-06-01'), new Date('2021-06-04'))];
  9. // [ 2021-06-01, 2021-06-02, 2021-06-03 ]