@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
35 lines (34 loc) • 1.06 kB
JavaScript
// src/internal/intervalCountHelpers.ts
/**
* Singular DateTimeUnit to its `Temporal.Duration` field name.
*
* Example lookups:
* - DURATION_FIELD_BY_UNIT.day => "days"
* - DURATION_FIELD_BY_UNIT.nanosecond => "nanoseconds"
*/
const DURATION_FIELD_BY_UNIT = {
year: "years",
month: "months",
week: "weeks",
day: "days",
hour: "hours",
minute: "minutes",
second: "seconds",
millisecond: "milliseconds",
microsecond: "microseconds",
nanosecond: "nanoseconds"
};
/**
* Extract the whole-unit span from a `Temporal.Duration` measured with `largestUnit: unit`.
*
* - Floors the field so a partial trailing amount never inflates a boundary count.
* - Does NOT validate the unit — caller ensures the duration was measured in it.
*
* @param duration Temporal.Duration produced by `until({ largestUnit: unit })`
* @param unit DateTimeUnit the duration was measured in
* @returns whole number of units spanned
*/
function getUnitSpan(duration, unit) {
return Math.floor(duration[DURATION_FIELD_BY_UNIT[unit]]);
}
export { DURATION_FIELD_BY_UNIT, getUnitSpan };