Created
January 14, 2025 16:39
-
-
Save papalardo/2b0ee396f4b100e3a11806d7695d2ada to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// new Date(Date.now() - Duration({ minutes: 5 }).toMilliseconds()) | |
// redis.set('key', Duration({ hours: 6 }).toMinutes('round'), 'value') | |
type Options = { days?: number; minutes?: number; hours?: number; seconds?: number; milliseconds?: number }; | |
const multiplies: Record<keyof Options, number> = { | |
days: 24 * 60 * 60_000, | |
hours: 60 * 60_000, | |
minutes: 60_000, | |
seconds: 1_000, | |
milliseconds: 1, | |
}; | |
const makeCallableResult = (time: number) => { | |
return (strategy: 'ceil' | 'floor' | 'round' | 'exact' = 'round') => { | |
if (strategy === 'exact') return time; | |
return Math[strategy](time); | |
}; | |
}; | |
export const Duration = (opts: Options) => { | |
let time = 0; | |
for (const keyTime of Object.keys(opts)) { | |
time += opts[keyTime] * multiplies[keyTime]; | |
} | |
return { | |
toSeconds: makeCallableResult(time / multiplies.seconds), | |
toMinutes: makeCallableResult(time / multiplies.minutes), | |
toHours: makeCallableResult(time / multiplies.hours), | |
toDays: makeCallableResult(time / multiplies.days), | |
toMilliseconds: makeCallableResult(time / multiplies.milliseconds), | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment