Library for authoring Zeichen plugins and themes.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.0 KiB

  1. export enum TimeDivision {
  2. MILLISECONDS,
  3. SECONDS,
  4. MINUTES,
  5. HOURS,
  6. DAYS
  7. }
  8. type GetTimeDifference = (a: Date, b: Date) => (c: TimeDivision) => number
  9. export const getTimeDifference: GetTimeDifference = (a, b) => {
  10. const ms = b.getTime() - a.getTime()
  11. const absoluteMs = ms < 0 ? -ms : ms
  12. return c => {
  13. let divisionDifference = absoluteMs
  14. if (c === TimeDivision.MILLISECONDS) {
  15. return divisionDifference
  16. }
  17. divisionDifference /= 1000
  18. if (c === TimeDivision.SECONDS) {
  19. return divisionDifference
  20. }
  21. divisionDifference /= 60
  22. if (c === TimeDivision.MINUTES) {
  23. return divisionDifference
  24. }
  25. divisionDifference /= 60
  26. if (c === TimeDivision.HOURS) {
  27. return divisionDifference
  28. }
  29. divisionDifference /= 24
  30. if (c === TimeDivision.DAYS) {
  31. return divisionDifference
  32. }
  33. throw new Error('Unknown time division.')
  34. }
  35. }
  36. type AddTime = (refDate: Date, increment: number) => (c: TimeDivision) => Date
  37. export const addTime: AddTime = (refDate, increment) => {
  38. const futureDate = new Date(refDate.getTime())
  39. return c => {
  40. let msIncrement = increment
  41. if (c === TimeDivision.MILLISECONDS) {
  42. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  43. return futureDate
  44. }
  45. msIncrement *= 1000
  46. if (c === TimeDivision.SECONDS) {
  47. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  48. return futureDate
  49. }
  50. msIncrement *= 60
  51. if (c === TimeDivision.MINUTES) {
  52. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  53. return futureDate
  54. }
  55. msIncrement *= 60
  56. if (c === TimeDivision.HOURS) {
  57. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  58. return futureDate
  59. }
  60. msIncrement *= 24
  61. if (c === TimeDivision.DAYS) {
  62. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  63. return futureDate
  64. }
  65. throw new Error('Unknown time division.')
  66. }
  67. }