Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance code and remove unused variables #70

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 8 additions & 12 deletions src/ap.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { dayPeriodMap, specDate, normStr } from "./common"
import type { LocalePeriod } from "./types"

/**
* Determines the correct value for am/pm by locale and memoizes it.
Expand All @@ -7,24 +8,19 @@ import { dayPeriodMap, specDate, normStr } from "./common"
*/
export function ap(ampm: "am" | "pm", locale: string): string {
const l = dayPeriodMap.get(locale)
if (l && l[ampm]) return l[ampm] as string
if (l?.[ampm]) return l[ampm] as string
const specimen = new Date(specDate)
specimen.setUTCHours(ampm === "am" ? 5 : 20)
const subparts = new Intl.DateTimeFormat(locale, {
const subParts = new Intl.DateTimeFormat(locale, {
timeStyle: "full",
timeZone: "UTC",
hour12: true,
})
.formatToParts(specimen)
.map(normStr)
const period = subparts.find((part) => part.type === "dayPeriod")
if (period) {
const localePeriods: { am?: string; pm?: string } = l || {}
dayPeriodMap.set(
locale,
Object.assign(localePeriods, { [ampm]: period.value })
)
return period.value
}
return ampm
const period = subParts.find((part) => part.type === "dayPeriod")
if (!period) return ampm
const localePeriod: LocalePeriod = l || {}
dayPeriodMap.set(locale, Object.assign(localePeriod, { [ampm]: period.value }))
return period.value
}
16 changes: 10 additions & 6 deletions src/common.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { date } from "./date"
import { ap } from "./ap"
import type {
DateInput,
NamedFormats,
FormatPattern,
FormatStyle,
Part,
FilledPart,
Format,
MaybeDateInput,
LocalePeriod,
} from "./types"

/**
Expand Down Expand Up @@ -124,7 +124,7 @@ export const tokens = /* @__PURE__ */ new Map(
/**
* A map of locale’s am/pm.
*/
export const dayPeriodMap: Map<string, { am?: string; pm?: string }> = new Map()
export const dayPeriodMap: Map<string, LocalePeriod> = new Map()

/**
* An array of all available date styles.
Expand Down Expand Up @@ -278,15 +278,19 @@ function createPartMap(
if (hour12.length) addValues(hour12, true)
if (hour24.length) addValues(hour24)

return valueParts.reduce((map, part) => {
map[part.type] = part.value
return map
}, {} as Record<keyof Intl.DateTimeFormatPartTypesRegistry, string>)
return valueParts.reduce(
(map, part) => {
map[part.type] = part.value
return map
},
{} as Record<keyof Intl.DateTimeFormatPartTypesRegistry, string>
)
}

/**
* Converts minutes (300) to an ISO8601 compatible offset (+0400 or +04:00).
* @param timeDiffInMins - The difference in minutes between two timezones.
* @param token
* @returns
*/
export function minsToOffset(timeDiffInMins: number, token: string = "Z"): string {
Expand Down
6 changes: 6 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/* Times in milliseconds */
export const ONE_SECOND_MS = 1_000
export const ONE_MINUTE_MS = 60_000
export const ONE_HOUR_MS = 3_600_000
export const ONE_DAY_MS = 86_400_000
export const SEVEN_DAY_MS = 604_800_000
8 changes: 3 additions & 5 deletions src/date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { MaybeDateInput } from "./types"
function normalize(date: string) {
const matches = date.match(iso8601Match)
if (matches && typeof matches[4] === "undefined") {
return (date += "T00:00:00")
return date + "T00:00:00"
}
return date
}
Expand All @@ -28,8 +28,6 @@ export function date(date?: MaybeDateInput): Date {
return d
}
date = date.trim()
if (iso8601(date)) {
return new Date(normalize(date))
}
throw new Error(`Non ISO 8601 compliant date (${date}).`)
if (!iso8601(date)) throw new Error(`Non ISO 8601 compliant date (${date}).`)
return new Date(normalize(date))
}
3 changes: 2 additions & 1 deletion src/dayOfYear.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { date } from "./date"
import type { MaybeDateInput } from "./types"
import { ONE_DAY_MS } from "./constants"

/**
* Gets the what day of the year a given date is. For example, August 1st is
Expand All @@ -11,6 +12,6 @@ export function dayOfYear(inputDate?: MaybeDateInput): number {
return Math.round(
(new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0).getTime() -
new Date(d.getFullYear(), 0, 0).getTime()) /
86400000
ONE_DAY_MS
)
}
7 changes: 2 additions & 5 deletions src/diffDays.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { diffMilliseconds } from "./diffMilliseconds"
import type { DateInput, MaybeDateInput } from "./types"
import { diffRound, type DiffRoundingMethod } from "./diffRound"
import { ONE_DAY_MS } from "./constants"

/**
* Returns the difference between 2 dates in days.
Expand Down Expand Up @@ -30,9 +31,5 @@ export function diffDays(
dateB?: MaybeDateInput,
roundingMethod?: DiffRoundingMethod
): number {
return diffRound(
// @ts-ignore
diffMilliseconds(dateA, dateB) / 86_400_000, // hour * 24
roundingMethod
)
return diffRound(diffMilliseconds(dateA, dateB) / ONE_DAY_MS, roundingMethod)
}
7 changes: 2 additions & 5 deletions src/diffHours.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { diffMilliseconds } from "./diffMilliseconds"
import { diffRound, type DiffRoundingMethod } from "./diffRound"
import type { DateInput, MaybeDateInput } from "./types"
import { ONE_HOUR_MS } from "./constants"

/**
* Returns the difference between 2 dates in hours.
Expand Down Expand Up @@ -31,9 +32,5 @@ export function diffHours(
dateB?: MaybeDateInput,
roundingMethod?: DiffRoundingMethod
): number {
return diffRound(
//@ts-ignore
diffMilliseconds(dateA, dateB) / 3_600_000, // 1000 * 60 * 60
roundingMethod
)
return diffRound(diffMilliseconds(dateA, dateB) / ONE_HOUR_MS, roundingMethod)
}
7 changes: 7 additions & 0 deletions src/diffMilliseconds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ export function diffMilliseconds(dateA: DateInput, dateB?: MaybeDateInput): numb
*/
export function diffMilliseconds(dateA: MaybeDateInput, dateB: DateInput): number

/**
* Returns the difference between 2 dates in milliseconds.
* @param [dateA] - A date to compare with the right date or null to compare with the current time
* @param dateB - A date to compare with the left date or null to compare with the current time
*/
export function diffMilliseconds(dateA: MaybeDateInput, dateB?: MaybeDateInput): number

export function diffMilliseconds(dateA: MaybeDateInput, dateB?: MaybeDateInput): number {
const left = date(dateA)
const right = date(dateB)
Expand Down
7 changes: 2 additions & 5 deletions src/diffMinutes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { DateInput, MaybeDateInput } from "./types"
import { diffMilliseconds } from "./diffMilliseconds"
import { diffRound, type DiffRoundingMethod } from "./diffRound"
import { ONE_MINUTE_MS } from "./constants"

/**
* Returns the difference between 2 dates in minutes.
Expand Down Expand Up @@ -31,9 +32,5 @@ export function diffMinutes(
dateB?: MaybeDateInput,
roundingMethod?: DiffRoundingMethod
): number {
return diffRound(
//@ts-ignore
diffMilliseconds(dateA, dateB) / 60_000,
roundingMethod
)
return diffRound(diffMilliseconds(dateA, dateB) / ONE_MINUTE_MS, roundingMethod)
}
11 changes: 10 additions & 1 deletion src/diffMonths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,28 @@ import { monthDays } from "./monthDays"
* @param [dateB] - A date to compare with the dateA date or nothing to compare with the current time
*/
export function diffMonths(dateA: DateInput, dateB?: MaybeDateInput): number

/**
* Returns the difference between 2 dates in months.
* @param [dateA] - A date to compare with the dateB date or null to compare with the current time
* @param dateB - A date to compare with the dateA date
*/
export function diffMonths(dateA: MaybeDateInput, dateB: DateInput): number

/**
* Returns the difference between 2 dates in months.
* @param [dateA] - A date to compare with the dateB date or null to compare with the current time
* @param dateB - A date to compare with the dateA date or null to compare with the current time
*/
export function diffMonths(dateA: MaybeDateInput, dateB?: MaybeDateInput): number

export function diffMonths(dateA: MaybeDateInput, dateB?: MaybeDateInput): number {
const l = date(dateA)
const r = date(dateB)
// if the dateB one is bigger, we switch them around as it's easier to do
if (l < r) {
const rs = diffMonths(r, l)
// Ensures we don't give back -0
return rs == 0 ? 0 : -rs
}

Expand All @@ -38,6 +47,6 @@ export function diffMonths(dateA: MaybeDateInput, dateB?: MaybeDateInput): numbe
months--
}
}
//ensures we don't give back -0
// Ensures we don't give back -0
return months == 0 ? 0 : months
}
7 changes: 2 additions & 5 deletions src/diffSeconds.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { diffMilliseconds } from "./diffMilliseconds"
import { DiffRoundingMethod, diffRound } from "./diffRound"
import type { DateInput, MaybeDateInput } from "./types"
import { ONE_SECOND_MS } from "./constants"

/**
* Returns the difference between 2 dates in seconds.
Expand Down Expand Up @@ -31,9 +32,5 @@ export function diffSeconds(
dateB?: MaybeDateInput,
roundingMethod?: DiffRoundingMethod
): number {
return diffRound(
// @ts-ignore
diffMilliseconds(dateA, dateB) / 1000,
roundingMethod
)
return diffRound(diffMilliseconds(dateA, dateB) / ONE_SECOND_MS, roundingMethod)
}
6 changes: 2 additions & 4 deletions src/diffWeeks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { diffMilliseconds } from "./diffMilliseconds"
import { DateInput, MaybeDateInput } from "./types"
import { diffRound, type DiffRoundingMethod } from "./diffRound"
import { SEVEN_DAY_MS } from "./constants"

/**
* Returns the difference between 2 dates in days.
Expand Down Expand Up @@ -31,8 +32,5 @@ export function diffWeeks(
dateB: DateInput,
roundingMethod?: DiffRoundingMethod
): number {
return diffRound(
diffMilliseconds(dateA, dateB) / 604800000, // day * 7
roundingMethod
)
return diffRound(diffMilliseconds(dateA, dateB) / SEVEN_DAY_MS, roundingMethod)
}
7 changes: 2 additions & 5 deletions src/diffYears.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@ export function diffYears(dateA: DateInput, dateB?: MaybeDateInput): number
*/
export function diffYears(dateA: MaybeDateInput, dateB: DateInput): number
export function diffYears(dateA: MaybeDateInput, dateB?: MaybeDateInput): number {
const r = Math.trunc(
//@ts-ignore
diffMonths(dateA, dateB) / 12
)
//ensures we don't give back -0
const r = Math.trunc(diffMonths(dateA, dateB) / 12)
// Ensures we don't give back -0
return r == 0 ? 0 : r
}
17 changes: 5 additions & 12 deletions src/format.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import { date } from "./date"
import { parts } from "./parts"
import { fill, getOffsetFormat } from "./common"
import type {
DateInput,
Format,
FormatOptions,
FormatStyle,
Part,
} from "./types"
import type { DateInput, Format, FormatOptions, Part } from "./types"
import { offset } from "./offset"
import { removeOffset } from "./removeOffset"
import { deviceLocale } from "./deviceLocale"
Expand Down Expand Up @@ -42,8 +36,10 @@ import { deviceTZ } from "./deviceTZ"
*
* @param inputDate - A date object or ISO 8601 string
* @param format - A format
* @param locale
* @param genitive
* @param partFilter
*/
export function format(options: FormatOptions): string
export function format(
inputDate: DateInput,
format?: Format,
Expand All @@ -60,10 +56,7 @@ export function format(
): string {
let tz: string | undefined, forceOffset: string | undefined

if (
typeof inputDateOrOptions === "object" &&
!(inputDateOrOptions instanceof Date)
) {
if (typeof inputDateOrOptions === "object" && !(inputDateOrOptions instanceof Date)) {
// Extract options from the object.
;({
date: inputDateOrOptions,
Expand Down
17 changes: 8 additions & 9 deletions src/formatStr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import type { Format, Part } from "./types"
* ```
* @param format - A format string or object.
* @param locale - A locale or en by default.
* @param escapeLiterals
* @param filterParts
*/
export function formatStr(
format: Format,
Expand All @@ -17,14 +19,11 @@ export function formatStr(
filterParts: (part: Part) => boolean = () => true
): string {
return parts(format, locale)
.filter(filterParts)
.reduce(
(f, p) =>
(f +=
escapeLiterals && p.partName === "literal"
? escapeTokens(p.token)
: p.token),
""
)
.reduce((f, p) => {
if (!filterParts(p)) return f
return (
f + (escapeLiterals && p.partName === "literal" ? escapeTokens(p.token) : p.token)
)
}, "")
.normalize("NFKC")
}
27 changes: 13 additions & 14 deletions src/iso8601.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,27 @@
* specificity.
*/
export const iso8601Match =
/^([0-9]{4})-([0-1][0-9])(?:-([0-3][0-9]))?(?:[T ]?([0-2][0-9])(?::([0-5][0-9]))?(?::([0-5][0-9]))?)?(?:\.[0-9]+)?(Z|(?:\+|\-)[0-9]{2}:?[0-9]{2})?$/
/^([0-9]{4})-([0-1][0-9])(?:-([0-3][0-9]))?(?:[T ]?([0-2][0-9])(?::([0-5][0-9]))?(?::([0-5][0-9]))?)?(?:\.[0-9]+)?(Z|[+\-][0-9]{2}:?[0-9]{2})?$/

/**
* True when the date string is valid ISO 8601.
* @param date - A date string.
*/
export function iso8601(date: string): boolean {
const matches = date.match(iso8601Match)
if (matches) {
const month = Number(matches[2])
if (month < 1 || month > 12) return false
if (!matches) return false

if (typeof matches[3] !== undefined) {
const date = Number(matches[3])
if (date < 1 || date > 31) return false
}
if (typeof matches[4] !== undefined) {
const hours = Number(matches[4])
if (hours < 0 || hours > 23) return false
}
const month = Number(matches[2])
if (month < 1 || month > 12) return false

return true
if (typeof matches[3] !== undefined) {
const date = Number(matches[3])
if (date < 1 || date > 31) return false
}
return false
if (typeof matches[4] !== undefined) {
const hours = Number(matches[4])
if (hours < 0 || hours > 23) return false
}

return true
}
Loading