|
@@ -0,0 +1,81 @@ |
|
|
|
|
|
export enum TimeDivision { |
|
|
|
|
|
MILLISECONDS, |
|
|
|
|
|
SECONDS, |
|
|
|
|
|
MINUTES, |
|
|
|
|
|
HOURS, |
|
|
|
|
|
DAYS |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
type GetTimeDifference = (a: Date, b: Date) => (c: TimeDivision) => number |
|
|
|
|
|
|
|
|
|
|
|
export const getTimeDifference: GetTimeDifference = (a, b) => { |
|
|
|
|
|
const ms = b.getTime() - a.getTime() |
|
|
|
|
|
const absoluteMs = ms < 0 ? -ms : ms |
|
|
|
|
|
|
|
|
|
|
|
return c => { |
|
|
|
|
|
let divisionDifference = absoluteMs |
|
|
|
|
|
if (c === TimeDivision.MILLISECONDS) { |
|
|
|
|
|
return divisionDifference |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
divisionDifference /= 1000 |
|
|
|
|
|
if (c === TimeDivision.SECONDS) { |
|
|
|
|
|
return divisionDifference |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
divisionDifference /= 60 |
|
|
|
|
|
if (c === TimeDivision.MINUTES) { |
|
|
|
|
|
return divisionDifference |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
divisionDifference /= 60 |
|
|
|
|
|
if (c === TimeDivision.HOURS) { |
|
|
|
|
|
return divisionDifference |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
divisionDifference /= 24 |
|
|
|
|
|
if (c === TimeDivision.DAYS) { |
|
|
|
|
|
return divisionDifference |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
throw new Error('Unknown time division.') |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
type AddTime = (refDate: Date, increment: number) => (c: TimeDivision) => Date |
|
|
|
|
|
|
|
|
|
|
|
export const addTime: AddTime = (refDate, increment) => { |
|
|
|
|
|
const futureDate = new Date(refDate.getTime()) |
|
|
|
|
|
return c => { |
|
|
|
|
|
let msIncrement = increment |
|
|
|
|
|
if (c === TimeDivision.MILLISECONDS) { |
|
|
|
|
|
futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement) |
|
|
|
|
|
return futureDate |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
msIncrement *= 1000 |
|
|
|
|
|
if (c === TimeDivision.SECONDS) { |
|
|
|
|
|
futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement) |
|
|
|
|
|
return futureDate |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
msIncrement *= 60 |
|
|
|
|
|
if (c === TimeDivision.MINUTES) { |
|
|
|
|
|
futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement) |
|
|
|
|
|
return futureDate |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
msIncrement *= 60 |
|
|
|
|
|
if (c === TimeDivision.HOURS) { |
|
|
|
|
|
futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement) |
|
|
|
|
|
return futureDate |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
msIncrement *= 24 |
|
|
|
|
|
if (c === TimeDivision.DAYS) { |
|
|
|
|
|
futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement) |
|
|
|
|
|
return futureDate |
|
|
|
|
|
} |
|
|
|
|
|
throw new Error('Unknown time division.') |
|
|
|
|
|
} |
|
|
|
|
|
} |