Skip to content

feat: add parseHumanDuration and defineHumanQuantityParser functions #332

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

Open
wants to merge 5 commits 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
8 changes: 5 additions & 3 deletions .github/next-minor.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ The `####` headline should be short and descriptive of the new functionality. In

## New Functions

####
#### `parseHumanDuration` function

## New Features
https://github.com/radashi-org/radashi/pull/332

####
#### `defineHumanQuantityParser` function

https://github.com/radashi-org/radashi/pull/332
11 changes: 11 additions & 0 deletions benchmarks/number/parseHumanDuration.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as _ from 'radashi'

describe('parseHumanDuration', () => {
bench('with string', () => {
_.parseHumanDuration('5 minutes')
})

bench('with number', () => {
_.parseHumanDuration(500)
})
})
56 changes: 56 additions & 0 deletions docs/number/parseHumanDuration.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
---
title: parseHumanDuration
description: Parses a human duration string into milliseconds
since: 12.3.0
---

### Usage

Parse a human duration string like "1 hour", "2 seconds" into milliseconds.
If a number is passed instead of a duration string, it is returned directly assuming milliseconds.

```ts
import * as _ from 'radashi'

_.parseHumanDuration('1 second') // => 1_000
_.parseHumanDuration('1h') // => 3_600_000
_.parseHumanDuration('1 hour') // => 3_600_000
_.parseHumanDuration('1.5 hours') // => 5_400_000
_.parseHumanDuration('-1h') // => -3_600_000
_.parseHumanDuration(500) // => 500
```

### Custom units

You can define custom units by passing a `units` object to the `defineHumanQuantityParser` function.

```ts
import * as _ from 'radashi'

const distanceParser = _.defineHumanQuantityParser({
units: {
kilometer: 1_000,
mile: 1_852,
yard: 0.9144,
foot: 0.3048,
meter: 1,
},
short: {
km: 'kilometer',
mi: 'mile',
yd: 'yard',
ft: 'foot',
m: 'meter',
},
})

distanceParser('1 kilometer') // => 1_000
distanceParser('1km') // => 1_000
distanceParser('1 mile') // => 1_852
distanceParser('1mi') // => 1_852
distanceParser('1 yard') // => 0.9144
distanceParser('1yd') // => 0.9144
distanceParser('1 foot') // => 0.3048
distanceParser('1ft') // => 0.3048
distanceParser('1 meter') // => 1
```
2 changes: 1 addition & 1 deletion scripts/release-notes/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"private": true,
"type": "module",
"private": true,
"dependencies": {
"@anthropic-ai/sdk": "^0.25.0",
"@octokit/rest": "^21.0.2",
Expand Down
1 change: 1 addition & 0 deletions src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export * from './number/round.ts'
export * from './number/sum.ts'
export * from './number/toFloat.ts'
export * from './number/toInt.ts'
export * from './number/parseHumanDuration.ts'

export * from './object/assign.ts'
export * from './object/clone.ts'
Expand Down
126 changes: 126 additions & 0 deletions src/number/parseHumanDuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { isNumber } from 'radashi'

export type HumanQuantity<
Unit extends string,
ShortUnit extends string = never,
> = `1 ${Unit}` | `${number} ${Unit}s` | `${number}${ShortUnit}`

export type HumanQuantityOptions<
Unit extends string = string,
ShortUnit extends string = string,
> = {
/**
* Time units mapping
*/
units: Record<Unit, number>
/**
* Aliases for time units
*/
short?: Record<ShortUnit, Unit>
}

/**
* Defines a parser for human quantity strings
*
* @see https://radashi.js.org/reference/number/parseHumanDuration
* @example
* ```ts
* const distanceParser = _.defineHumanQuantityParser({
* units: {
* kilometer: 1_000,
* mile: 1_852,
* yard: 0.9144,
* foot: 0.3048,
* meter: 1,
* },
* short: {
* km: 'kilometer',
* mi: 'mile',
* yd: 'yard',
* ft: 'foot',
* m: 'meter',
* },
* })
*
* distanceParser("1 kilometer") // => 1_000
* distanceParser("1 mile") // => 1_852
* distanceParser("1 yard") // => 0.9144
* distanceParser("1ft") // => 0.3048
* distanceParser("1 meter") // => 1
* ```
*/
export function defineHumanQuantityParser<
Unit extends string,
ShortUnit extends string = never,
>({ units, short }: HumanQuantityOptions<Unit, ShortUnit>) {
return (quantity: HumanQuantity<Unit, ShortUnit>): number => {
const match = quantity.match(/^(-?\d+(?:\.\d+)?) ?(\w+)?s?$/)
if (!match) {
throw new Error(`Invalid quantity, cannot parse: ${quantity}`)
}

let unit = match[2] as Unit | ShortUnit
unit = short && unit in short ? short[unit as ShortUnit] : (unit as Unit)

const count = Number.parseFloat(match[1])
if (Math.abs(count) > 1 && unit.endsWith('s')) {
unit = unit.substring(0, unit.length - 1) as Unit
}

if (!units[unit]) {
throw new Error(
`Invalid unit: ${unit}, makes sure it is one of: ${Object.keys(units).join(', ')}`,
)
}

return count * units[unit]
}
}

export type HumanDuration = HumanQuantity<
'week' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond',
'w' | 'd' | 'h' | 'm' | 's' | 'ms'
>

/**
* Parses a human duration string into milliseconds
*
* @see https://radashi.js.org/reference/number/parseHumanDuration
* @example
* ```ts
* parseHumanDuration("1 second") // => 1_000
* parseHumanDuration("1h") // => 3_600_000
* parseHumanDuration("1 hour") // => 3_600_000
* parseHumanDuration("1.5 hours") // => 5_400_000
* parseHumanDuration("-1h") // => -3_600_000
* parseHumanDuration(500) // => 500
* ```
*/
export function parseHumanDuration(
humanDuration: HumanDuration | number,
): number {
if (isNumber(humanDuration)) {
return humanDuration
}

const parser = defineHumanQuantityParser({
units: {
week: 7 * 24 * 60 * 60 * 1_000,
day: 24 * 60 * 60 * 1_000,
hour: 60 * 60 * 1_000,
minute: 60 * 1_000,
second: 1_000,
millisecond: 1,
},
short: {
w: 'week',
d: 'day',
h: 'hour',
m: 'minute',
s: 'second',
ms: 'millisecond',
},
})

return parser(humanDuration)
}
94 changes: 94 additions & 0 deletions tests/number/parseHumanDuration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import * as _ from 'radashi'

describe('parseHumanDuration', () => {
test('returned values', () => {
// milliseconds
expect(_.parseHumanDuration('1 millisecond')).toBe(1)
expect(_.parseHumanDuration('1.5 milliseconds')).toBe(1.5)
expect(_.parseHumanDuration('2 milliseconds')).toBe(2)
expect(_.parseHumanDuration('1ms')).toBe(1)
expect(_.parseHumanDuration('-2ms')).toBe(-2)

// seconds
expect(_.parseHumanDuration('1 second')).toBe(1_000)
expect(_.parseHumanDuration('1.5 seconds')).toBe(1_500)
expect(_.parseHumanDuration('2 seconds')).toBe(2_000)
expect(_.parseHumanDuration('1s')).toBe(1_000)
expect(_.parseHumanDuration('-2s')).toBe(-2_000)

// minutes
expect(_.parseHumanDuration('1 minute')).toBe(60_000)
expect(_.parseHumanDuration('1.5 minutes')).toBe(90_000)
expect(_.parseHumanDuration('2 minutes')).toBe(120_000)
expect(_.parseHumanDuration('1m')).toBe(60_000)
expect(_.parseHumanDuration('-2m')).toBe(-120_000)

// hours
expect(_.parseHumanDuration('1 hour')).toBe(3_600_000)
expect(_.parseHumanDuration('1.5 hours')).toBe(5_400_000)
expect(_.parseHumanDuration('2 hours')).toBe(7_200_000)
expect(_.parseHumanDuration('1h')).toBe(3_600_000)
expect(_.parseHumanDuration('-2h')).toBe(-7_200_000)

// days
expect(_.parseHumanDuration('1 day')).toBe(86_400_000)
expect(_.parseHumanDuration('1.5 days')).toBe(129_600_000)
expect(_.parseHumanDuration('2 days')).toBe(172_800_000)
expect(_.parseHumanDuration('1d')).toBe(86_400_000)
expect(_.parseHumanDuration('-2d')).toBe(-172_800_000)

// weeks
expect(_.parseHumanDuration('1 week')).toBe(604_800_000)
expect(_.parseHumanDuration('1.5 weeks')).toBe(907_200_000)
expect(_.parseHumanDuration('2 weeks')).toBe(1_209_600_000)
expect(_.parseHumanDuration('1w')).toBe(604800000)
expect(_.parseHumanDuration('-2w')).toBe(-1_209_600_000)
})

test('failures on invalid input', () => {
expect(() =>
_.parseHumanDuration('An invalid string' as _.HumanDuration),
).toThrow(/Invalid quantity, cannot parse: An invalid string/)
expect(() => _.parseHumanDuration('abc weeks' as _.HumanDuration)).toThrow(
/Invalid quantity, cannot parse: abc weeks/,
)
expect(() => _.parseHumanDuration('3 unknown' as _.HumanDuration)).toThrow(
/Invalid unit: unknown, makes sure it is one of: week, day, hour, minute, second, millisecond/,
)
})

test('is does nothing when parameter is alaready a number', () => {
expect(_.parseHumanDuration(50)).toBe(50)
})
})

describe('defineHumanQuantityParser', () => {
const distanceParser = _.defineHumanQuantityParser({
units: {
kilometer: 1_000,
mile: 1_852,
yard: 0.9144,
foot: 0.3048,
meter: 1,
},
short: {
km: 'kilometer',
mi: 'mile',
yd: 'yard',
ft: 'foot',
m: 'meter',
},
})

test('returned values', () => {
expect(distanceParser('1 kilometer')).toBe(1_000)
expect(distanceParser('1km')).toBe(1_000)
expect(distanceParser('1 mile')).toBe(1_852)
expect(distanceParser('1mi')).toBe(1_852)
expect(distanceParser('1 yard')).toBe(0.9144)
expect(distanceParser('1yd')).toBe(0.9144)
expect(distanceParser('1 foot')).toBe(0.3048)
expect(distanceParser('1ft')).toBe(0.3048)
expect(distanceParser('1 meter')).toBe(1)
})
})
Loading