Skip to content
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
2 changes: 2 additions & 0 deletions .github/workflows/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ jobs:
run: bun install
- name: Build
run: bun run build
- name: Test types
run: bun run test:types
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## Changelog

#### v2.1.0
- added: TimeString/TimeUnit types - duration strings passed to ms/seconds/datePlus are now type-checked
- BREAKING (types only): TS code passing plain strings (e.g. user input) must cast via `as TimeString` - runtime behavior is unchanged
#### v2.0.0
- BREAKING: to allow 0, false, and '0' as valid arguments for ms, tests had to be changed.
- removed: sourcemaps in dist version (additional size savings)
Expand Down
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ Use Luke's if you want the absolute fastest parsing, or itty if you want some of

## seconds/ms
<h4>
<code>seconds(duration: string) => number</code><br />
<code>ms(duration: string) => number</code><br />
<code>seconds(duration: TimeString | number) => number</code><br />
<code>ms(duration: TimeString | number) => number</code><br />
</h4>

TTL math is a maintenance nightmare. It's a pain to write, a pain to read, and when you update the math later, you'll probably forget to update the comment, causing all sorts of mayhem.
Expand All @@ -76,6 +76,14 @@ seconds('2 weeks') // 1209600
ms('2 weeks') // 1209600000
```

Duration strings are typed as `TimeString`, so typos like `ms('2 weekz')` fail at compile time rather than silently misbehaving. If you're parsing arbitrary user input (that you've validated yourself), cast it:

```ts
import { ms, type TimeString } from 'itty-time'

ms(userInput as TimeString)
```

## duration
<h4>
<code>duration(ms: number) => string</code>
Expand Down Expand Up @@ -114,7 +122,7 @@ duration(3750000, { join: false })

## datePlus
<h4>
<code>datePlus(duration: string, from = new Date) => Date</code>
<code>datePlus(duration: TimeString | number, from = new Date) => Date</code>
</h4>

Sometimes you need a TTL for some point in the future, but sometimes you need the actual date. You could convert it all yourself... or use this.
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"scripts": {
"dev": "bun test --watch --coverage",
"test": "bun test --coverage",
"test:types": "tsc -p tsconfig.spec.json",
"lint": "itty lint",
"build": "itty lint && itty build --hybrid",
"release": "itty release --prepare --tag --push",
Expand Down
4 changes: 2 additions & 2 deletions src/datePlus.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'bun:test'
import { datePlus } from './datePlus'
import { ms } from './ms'
import { ms, type TimeString } from './ms'

describe('datePlus(duration: string, from?: Date): Date', () => {
type DatePlusTest = [duration: string]
type DatePlusTest = [duration: TimeString]

const tests: DatePlusTest[] = [
['5 seconds'],
Expand Down
3 changes: 2 additions & 1 deletion src/datePlus.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ms } from './ms'
import { type TimeString } from './lib/units'

// FUNCTION: get future date from a duration string (e.g. datePlus('3 hours'))
export const datePlus = (duration: string | number, from = new Date): Date =>
export const datePlus = (duration: TimeString | number, from = new Date): Date =>
new Date(from.getTime() + ms(duration))
4 changes: 2 additions & 2 deletions src/duration.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { describe, expect, it } from 'bun:test'
import { duration } from './duration'
import { ms } from './ms'
import { ms, type TimeString } from './ms'

const BASE = '1.1 weeks'
const EXPECTED = '1 week, 16 hours, 48 minutes'

describe('duration(ms: number, options?: durationOptions)', () => {
describe('reverse-parses ms (number) into a readable string', () => {
const tests = [
const tests: { original: TimeString, parts?: number, expected?: string }[] = [
{ original: BASE, expected: '1 week, 16 hours, 48 minutes' },
{ original: BASE, parts: 2, expected: '1 week, 16.8 hours' },
{ original: BASE, parts: 1, expected: '1.1 weeks' },
Expand Down
2 changes: 1 addition & 1 deletion src/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'bun:test'
import * as exports from './index'

const expected = [
const expected: (keyof typeof exports)[] = [
'seconds',
'ms',
'duration',
Expand Down
13 changes: 13 additions & 0 deletions src/lib/units.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,19 @@ const
month = day * 30,
year = day * 365.25

export type TimeUnit =
| 'ms'
| 'millisecond' | 'milliseconds'
| 'second' | 'seconds'
| 'minute' | 'minutes'
| 'hour' | 'hours'
| 'day' | 'days'
| 'week' | 'weeks'
| 'month' | 'months'
| 'year' | 'years'

export type TimeString = `${number}` | `${number} ${TimeUnit}`

export const units: Record<string, number> = {
year,
month,
Expand Down
11 changes: 6 additions & 5 deletions src/ms.spec.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import { describe, expect, it } from 'bun:test'
import { ms } from './ms'
import { ms, type TimeString } from './ms'

describe('ms(duration: string): number', () => {
type MsTest = [duration: string | number, expected: number]
type MsTest = [duration: TimeString | number, expected: number]

const tests: MsTest[] = [
['1 minutes', 60 * 1000],
['24 hour', 60 * 60 * 24 * 1000],
['2 years', 2 * 365.25 * 24 * 60 * 60 * 1000],
['321 day', 60 * 60 * 24 * 321 * 1000],
['30.5 seconds', 30.5 * 1000],
['30.5 seconds', 30.5 * 1000],
['30.5 seconds' as TimeString, 30.5 * 1000], // extra whitespace still parses at runtime
[4001, 4001], // a number is assumed to be a number
['100', 100], // string of a number is assumed to be ms
['100 ms', 100], // can handle ms
['100apple', NaN], // can handle ms
['100 milliseconds', 100], // can handle milliseconds
['100apple' as TimeString, NaN], // unparsable strings return NaN at runtime
]

describe('returns number of Ms', () => {
Expand All @@ -35,7 +36,7 @@ describe('ms(duration: string): number', () => {
{ type: 'date', value: date, returns: +date },
{ type: 'false', value: false, returns: 0 },
{ type: '0 (string)', value: '0', returns: 0 },
{ type: '0', value: '0', returns: 0 },
{ type: '0', value: 0, returns: 0 },
{ type: 'unparsable string', value: '456apple', returns: NaN },
{ type: 'object', value: {}, throws: true },
{ type: 'function', value: () => {}, throws: true },
Expand Down
6 changes: 4 additions & 2 deletions src/ms.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { units } from './lib/units'
import { units, type TimeString } from './lib/units'

export type { TimeString, TimeUnit } from './lib/units'

// FUNCTION: get number of seconds from a duration string
export const ms = (duration: string | number): number => {
export const ms = (duration: TimeString | number): number => {
if (!isNaN(+duration)) return +duration

// @ts-ignore
Expand Down
3 changes: 2 additions & 1 deletion src/seconds.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { describe, expect, it } from 'bun:test'
import { seconds } from './seconds'
import { type TimeString } from './lib/units'

describe('seconds(duration: string): number', () => {
type SecondsTest = [duration: string | number, expected: number]
type SecondsTest = [duration: TimeString | number, expected: number]

const tests: SecondsTest[] = [
['5 seconds', 5],
Expand Down
3 changes: 2 additions & 1 deletion src/seconds.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ms } from './ms'
import { type TimeString } from './lib/units'

export const seconds = (duration: string | number): number =>
export const seconds = (duration: TimeString | number): number =>
ms(duration) / 1000
46 changes: 46 additions & 0 deletions src/types.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'bun:test'
import { datePlus } from './datePlus'
import { ms } from './ms'
import { seconds } from './seconds'
import { type TimeString } from './lib/units'

// The @ts-expect-error assertions below are verified by `bun run test:types`,
// since bun test does not type-check.
describe('TimeString type checking', () => {
it('accepts every format the type allows', () => {
const durations: [duration: TimeString, expected: number][] = [
['100', 100],
['100 ms', 100],
['100 millisecond', 100],
['100 milliseconds', 100],
['30.5 seconds', 30.5 * 1000],
['-30 minutes', -30 * 60 * 1000],
['1.5 hours', 1.5 * 60 * 60 * 1000],
['1 day', 24 * 60 * 60 * 1000],
['2 weeks', 2 * 7 * 24 * 60 * 60 * 1000],
['3 months', 3 * 30 * 24 * 60 * 60 * 1000],
['4 years', 4 * 365.25 * 24 * 60 * 60 * 1000],
]

for (const [duration, expected] of durations) {
expect(ms(duration)).toBe(expected)
expect(seconds(duration)).toBe(expected / 1000)
expect(+datePlus(duration, new Date(0))).toBe(expected)
}
})

it('rejects invalid durations at compile time', () => {
// @ts-expect-error - arbitrary strings are not valid durations
expect(ms('lskdjfsdlkfjsdlfkjsd')).toBeNaN()

// @ts-expect-error - duration values must be numeric
expect(seconds('one hour')).toBeNaN()

// unit typos silently fall back to ms at runtime - the type catches them
// @ts-expect-error - unsupported units are rejected
expect(ms('2 weekz')).toBe(2)

// @ts-expect-error - unsupported units are rejected
expect(+datePlus('2 apples', new Date(1000))).toBe(1002)
})
})
9 changes: 9 additions & 0 deletions tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": true,
"types": ["bun"]
},
"exclude": ["node_modules", "dist", "examples"],
"include": ["src"]
}
Loading