-
Notifications
You must be signed in to change notification settings - Fork 41
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
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
033e74c
feat: parseHumanDuration implementation
hugo082 03feb0d
doc: parseHumanDuration and defineHumanQuantityParser usage
hugo082 f3b61e3
fix: reviews & formatting
hugo082 36b24b4
chore: format
hugo082 cffcd38
chore: bench & doc
hugo082 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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) | ||
}) | ||
}) |
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
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 | ||
``` |
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
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
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
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) | ||
} |
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
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) | ||
}) | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.