intervalToMilliseconds.tsx 632 B

123456789101112131415161718192021222324
  1. /**
  2. * Convert an interval string into a number of seconds.
  3. * This allows us to create end timestamps from starting ones
  4. * enabling us to find events in narrow windows.
  5. *
  6. * @param {String} interval The interval to convert.
  7. * @return {Integer}
  8. */
  9. export function intervalToMilliseconds(interval: string): number {
  10. const pattern = /^(\d+)(w|d|h|m)$/;
  11. const matches = pattern.exec(interval);
  12. if (!matches) {
  13. return 0;
  14. }
  15. const [, value, unit] = matches;
  16. const multipliers = {
  17. w: 60 * 60 * 24 * 7,
  18. d: 60 * 60 * 24,
  19. h: 60 * 60,
  20. m: 60,
  21. };
  22. return parseInt(value, 10) * multipliers[unit] * 1000;
  23. }