@alwatr/parse-duration 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # 1.0.0 (2024-01-16)
7
+
8
+ ### Bug Fixes
9
+
10
+ * **parse-duration:** remove unused variables ([500f272](https://github.com/Alwatr/nanolib/commit/500f2727373daf12b6b8b84032244a88f197948e)) by @adltalab
11
+
12
+ ### Features
13
+
14
+ * **parse-duration:** rewrite module 🤦🏻 ([be62163](https://github.com/Alwatr/nanolib/commit/be6216345cb3d4458307f55b8ae44f5ac60dda89)) by @AliMD
15
+ * **parse-duration:** rewrite with document ([43ffecc](https://github.com/Alwatr/nanolib/commit/43ffeccbc4a859ad838938a63fd52c82654cc9bb)) by @njfamirm
16
+ * **parse-duration:** seperate parseDuration from `@alwatr/math` ([f5e32d0](https://github.com/Alwatr/nanolib/commit/f5e32d080be1b5355463f77a2f23fbd0955b8b67)) by @adltalab
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 S. Ali Mihandoost
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ # Parse-duration
2
+
3
+ A simple utility to parse a duration string into milliseconds number.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ yarn add @alwatr/parse-duration
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ import {parseDuration} from '@alwatr/parse-duration';
15
+
16
+ parseDuration('10s'); // 10,000
17
+ parseDuration('10m'); // 600,000
18
+ parseDuration('10h'); // 36,000,000
19
+ parseDuration('10d'); // 864,000,000
20
+ parseDuration('10w'); // 6,048,000,000
21
+ parseDuration('10M'); // 25,920,000,000
22
+ parseDuration('10y'); // 315,360,000,000
23
+ parseDuration('10d', 'h'); // 240
24
+ ```
25
+
26
+ ### Unit Table
27
+
28
+ | Unit | Description |
29
+ |------|--------|
30
+ | `s` | Second |
31
+ | `m` | Minute |
32
+ | `h` | Hour |
33
+ | `d` | Day |
34
+ | `w` | Week |
35
+ | `M` | Month |
36
+ | `y` | Year |
package/dist/main.cjs ADDED
@@ -0,0 +1,3 @@
1
+ /* @alwatr/parse-duration v1.0.0 */
2
+ "use strict";var e=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var p=(r,n)=>{for(var t in n)e(r,t,{get:n[t],enumerable:!0})},w=(r,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of m(n))!d.call(r,o)&&o!==t&&e(r,o,{get:()=>n[o],enumerable:!(i=f(n,o))||i.enumerable});return r};var D=r=>w(e({},"__esModule",{value:!0}),r);var h={};p(h,{parseDuration:()=>b});module.exports=D(h);var c=require("@alwatr/is-number"),a={s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:2592e6,y:31536e6},b=(r,n)=>{let t=r.slice(0,r.length-1);if(!(0,c.isNumber)(t))throw new Error("not_a_number");let i=+t,o=r.slice(-1),u=a[o];if(u===void 0)throw new Error("invalid_unit",{cause:{duration:r}});let s=i*u;if(n===void 0)return s;let _=a[n];if(_===void 0)throw new Error("invalid_unit",{cause:{toUnit:n}});return s/_};0&&(module.exports={parseDuration});
3
+ //# sourceMappingURL=main.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/main.ts"],
4
+ "sourcesContent": ["import {isNumber} from '@alwatr/is-number';\n\n/**\n * Unit conversion table\n */\nconst unitConversion_ = {\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n w: 604_800_000,\n M: 2_592_000_000,\n y: 31_536_000_000,\n} as const;\n\n/**\n * Duration unit: `s` for seconds, `m` for minutes, `h` for hours, `d` for days, `w` for weeks, `M` for months, `y` for years.\n */\nexport type DurationUnit = keyof typeof unitConversion_;\n\n/**\n * Duration string format: `number + unit`, for example `10m` means 10 minutes.\n */\nexport type DurationString = `${number}${DurationUnit}`;\n\n/**\n * Parse duration string to milliseconds number.\n *\n * @param duration - duration string, for example `10m` means 10 minutes.\n * @param toUnit - convert to unit, default is `ms` for milliseconds.\n * @return duration in milliseconds.\n * @example\n * ```ts\n * parseDuration('10m'); // 600000\n * parseDuration('10m', 's'); // 600\n * ```\n */\nexport const parseDuration = (duration: DurationString, toUnit?: DurationUnit): number => {\n const durationNumberStr = duration.slice(0, duration.length - 1);\n if (!isNumber(durationNumberStr)) {\n throw new Error(`not_a_number`);\n }\n const durationNumber = +durationNumberStr;\n const durationUnit = duration.slice(-1) as DurationUnit;\n const factor = unitConversion_[durationUnit];\n if (factor === undefined) {\n throw new Error(`invalid_unit`, {cause: {duration}});\n }\n const ms = durationNumber * factor;\n if (toUnit === undefined) {\n return ms;\n }\n // else\n const toFactor = unitConversion_[toUnit];\n if (toFactor === undefined) {\n throw new Error(`invalid_unit`, {cause: {toUnit}});\n }\n return ms / toFactor;\n};\n"],
5
+ "mappings": ";yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAuB,6BAKjBC,EAAkB,CACtB,EAAG,IACH,EAAG,IACH,EAAG,KACH,EAAG,MACH,EAAG,OACH,EAAG,OACH,EAAG,OACL,EAwBaH,EAAgB,CAACI,EAA0BC,IAAkC,CACxF,IAAMC,EAAoBF,EAAS,MAAM,EAAGA,EAAS,OAAS,CAAC,EAC/D,GAAI,IAAC,YAASE,CAAiB,EAC7B,MAAM,IAAI,MAAM,cAAc,EAEhC,IAAMC,EAAiB,CAACD,EAClBE,EAAeJ,EAAS,MAAM,EAAE,EAChCK,EAASN,EAAgBK,CAAY,EAC3C,GAAIC,IAAW,OACb,MAAM,IAAI,MAAM,eAAgB,CAAC,MAAO,CAAC,SAAAL,CAAQ,CAAC,CAAC,EAErD,IAAMM,EAAKH,EAAiBE,EAC5B,GAAIJ,IAAW,OACb,OAAOK,EAGT,IAAMC,EAAWR,EAAgBE,CAAM,EACvC,GAAIM,IAAa,OACf,MAAM,IAAI,MAAM,eAAgB,CAAC,MAAO,CAAC,OAAAN,CAAM,CAAC,CAAC,EAEnD,OAAOK,EAAKC,CACd",
6
+ "names": ["main_exports", "__export", "parseDuration", "__toCommonJS", "import_is_number", "unitConversion_", "duration", "toUnit", "durationNumberStr", "durationNumber", "durationUnit", "factor", "ms", "toFactor"]
7
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Unit conversion table
3
+ */
4
+ declare const unitConversion_: {
5
+ readonly s: 1000;
6
+ readonly m: 60000;
7
+ readonly h: 3600000;
8
+ readonly d: 86400000;
9
+ readonly w: 604800000;
10
+ readonly M: 2592000000;
11
+ readonly y: 31536000000;
12
+ };
13
+ /**
14
+ * Duration unit: `s` for seconds, `m` for minutes, `h` for hours, `d` for days, `w` for weeks, `M` for months, `y` for years.
15
+ */
16
+ export type DurationUnit = keyof typeof unitConversion_;
17
+ /**
18
+ * Duration string format: `number + unit`, for example `10m` means 10 minutes.
19
+ */
20
+ export type DurationString = `${number}${DurationUnit}`;
21
+ /**
22
+ * Parse duration string to milliseconds number.
23
+ *
24
+ * @param duration - duration string, for example `10m` means 10 minutes.
25
+ * @param toUnit - convert to unit, default is `ms` for milliseconds.
26
+ * @return duration in milliseconds.
27
+ * @example
28
+ * ```ts
29
+ * parseDuration('10m'); // 600000
30
+ * parseDuration('10m', 's'); // 600
31
+ * ```
32
+ */
33
+ export declare const parseDuration: (duration: DurationString, toUnit?: DurationUnit) => number;
34
+ export {};
35
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,QAAA,MAAM,eAAe;;;;;;;;CAQX,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,OAAO,eAAe,CAAC;AAExD;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,GAAG,MAAM,GAAG,YAAY,EAAE,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,aAAa,aAAc,cAAc,WAAW,YAAY,KAAG,MAqB/E,CAAC"}
package/dist/main.mjs ADDED
@@ -0,0 +1,3 @@
1
+ /* @alwatr/parse-duration v1.0.0 */
2
+ import{isNumber as a}from"@alwatr/is-number";var u={s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:2592e6,y:31536e6},f=(n,r)=>{let t=n.slice(0,n.length-1);if(!a(t))throw new Error("not_a_number");let s=+t,_=n.slice(-1),o=u[_];if(o===void 0)throw new Error("invalid_unit",{cause:{duration:n}});let i=s*o;if(r===void 0)return i;let e=u[r];if(e===void 0)throw new Error("invalid_unit",{cause:{toUnit:r}});return i/e};export{f as parseDuration};
3
+ //# sourceMappingURL=main.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/main.ts"],
4
+ "sourcesContent": ["import {isNumber} from '@alwatr/is-number';\n\n/**\n * Unit conversion table\n */\nconst unitConversion_ = {\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n w: 604_800_000,\n M: 2_592_000_000,\n y: 31_536_000_000,\n} as const;\n\n/**\n * Duration unit: `s` for seconds, `m` for minutes, `h` for hours, `d` for days, `w` for weeks, `M` for months, `y` for years.\n */\nexport type DurationUnit = keyof typeof unitConversion_;\n\n/**\n * Duration string format: `number + unit`, for example `10m` means 10 minutes.\n */\nexport type DurationString = `${number}${DurationUnit}`;\n\n/**\n * Parse duration string to milliseconds number.\n *\n * @param duration - duration string, for example `10m` means 10 minutes.\n * @param toUnit - convert to unit, default is `ms` for milliseconds.\n * @return duration in milliseconds.\n * @example\n * ```ts\n * parseDuration('10m'); // 600000\n * parseDuration('10m', 's'); // 600\n * ```\n */\nexport const parseDuration = (duration: DurationString, toUnit?: DurationUnit): number => {\n const durationNumberStr = duration.slice(0, duration.length - 1);\n if (!isNumber(durationNumberStr)) {\n throw new Error(`not_a_number`);\n }\n const durationNumber = +durationNumberStr;\n const durationUnit = duration.slice(-1) as DurationUnit;\n const factor = unitConversion_[durationUnit];\n if (factor === undefined) {\n throw new Error(`invalid_unit`, {cause: {duration}});\n }\n const ms = durationNumber * factor;\n if (toUnit === undefined) {\n return ms;\n }\n // else\n const toFactor = unitConversion_[toUnit];\n if (toFactor === undefined) {\n throw new Error(`invalid_unit`, {cause: {toUnit}});\n }\n return ms / toFactor;\n};\n"],
5
+ "mappings": ";AAAA,OAAQ,YAAAA,MAAe,oBAKvB,IAAMC,EAAkB,CACtB,EAAG,IACH,EAAG,IACH,EAAG,KACH,EAAG,MACH,EAAG,OACH,EAAG,OACH,EAAG,OACL,EAwBaC,EAAgB,CAACC,EAA0BC,IAAkC,CACxF,IAAMC,EAAoBF,EAAS,MAAM,EAAGA,EAAS,OAAS,CAAC,EAC/D,GAAI,CAACH,EAASK,CAAiB,EAC7B,MAAM,IAAI,MAAM,cAAc,EAEhC,IAAMC,EAAiB,CAACD,EAClBE,EAAeJ,EAAS,MAAM,EAAE,EAChCK,EAASP,EAAgBM,CAAY,EAC3C,GAAIC,IAAW,OACb,MAAM,IAAI,MAAM,eAAgB,CAAC,MAAO,CAAC,SAAAL,CAAQ,CAAC,CAAC,EAErD,IAAMM,EAAKH,EAAiBE,EAC5B,GAAIJ,IAAW,OACb,OAAOK,EAGT,IAAMC,EAAWT,EAAgBG,CAAM,EACvC,GAAIM,IAAa,OACf,MAAM,IAAI,MAAM,eAAgB,CAAC,MAAO,CAAC,OAAAN,CAAM,CAAC,CAAC,EAEnD,OAAOK,EAAKC,CACd",
6
+ "names": ["isNumber", "unitConversion_", "parseDuration", "duration", "toUnit", "durationNumberStr", "durationNumber", "durationUnit", "factor", "ms", "toFactor"]
7
+ }
package/package.json ADDED
@@ -0,0 +1,83 @@
1
+ {
2
+ "name": "@alwatr/parse-duration",
3
+ "version": "1.0.0",
4
+ "description": "A simple utility to parse a duration string into milliseconds number.",
5
+ "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
6
+ "keywords": [
7
+ "parse",
8
+ "duration",
9
+ "time",
10
+ "parse-duration",
11
+ "cross-platform",
12
+ "ECMAScript",
13
+ "typescript",
14
+ "javascript",
15
+ "node",
16
+ "nodejs",
17
+ "browser",
18
+ "esm",
19
+ "module",
20
+ "utility",
21
+ "util",
22
+ "utils",
23
+ "nanolib",
24
+ "alwatr"
25
+ ],
26
+ "type": "module",
27
+ "main": "./dist/main.cjs",
28
+ "module": "./dist/main.mjs",
29
+ "types": "./dist/main.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "import": "./dist/main.mjs",
33
+ "require": "./dist/main.cjs",
34
+ "types": "./dist/main.d.ts"
35
+ }
36
+ },
37
+ "license": "MIT",
38
+ "files": [
39
+ "**/*.{js,mjs,cjs,map,d.ts,html,md}",
40
+ "!demo/**/*"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "https://github.com/Alwatr/nanolib",
48
+ "directory": "packages/parse-duration"
49
+ },
50
+ "homepage": "https://github.com/Alwatr/nanolib/tree/next/packages/parse-duration#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/Alwatr/nanolib/issues"
53
+ },
54
+ "prettier": "@alwatr/prettier-config",
55
+ "scripts": {
56
+ "b": "yarn run build",
57
+ "t": "yarn run test",
58
+ "w": "yarn run watch",
59
+ "c": "yarn run clean",
60
+ "cb": "yarn run clean && yarn run build",
61
+ "d": "yarn run build:es && yarn node --enable-source-maps --trace-warnings",
62
+ "build": "yarn run build:ts & yarn run build:es",
63
+ "build:es": "nano-build --preset=module",
64
+ "build:ts": "tsc --build",
65
+ "test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" jest",
66
+ "watch": "yarn run watch:ts & yarn run watch:es",
67
+ "watch:es": "yarn run build:es --watch",
68
+ "watch:ts": "yarn run build:ts --watch --preserveWatchOutput",
69
+ "clean": "rm -rfv dist *.tsbuildinfo"
70
+ },
71
+ "dependencies": {
72
+ "@alwatr/is-number": "^1.0.0"
73
+ },
74
+ "devDependencies": {
75
+ "@alwatr/nano-build": "^1.3.1",
76
+ "@alwatr/prettier-config": "^1.0.4",
77
+ "@alwatr/tsconfig-base": "^1.1.1",
78
+ "@types/node": "^20.11.3",
79
+ "jest": "^29.7.0",
80
+ "typescript": "^5.3.3"
81
+ },
82
+ "gitHead": "369887cfdcbf5c6f3899880a5e217b102b36706c"
83
+ }
@@ -0,0 +1,41 @@
1
+ import {parseDuration} from '@alwatr/parse-duration';
2
+
3
+ describe('@alwatr/parse-duration', () => {
4
+ it('should parse duration in seconds', () => {
5
+ expect(parseDuration('5s')).toBe(5 * 1000);
6
+ });
7
+
8
+ it('should parse duration in minutes', () => {
9
+ expect(parseDuration('3m')).toBe(3 * 60 * 1000);
10
+ });
11
+
12
+ it('should parse duration in hours', () => {
13
+ expect(parseDuration('2h')).toBe(2 * 60 * 60 * 1000);
14
+ });
15
+
16
+ it('should convert duration to specified unit', () => {
17
+ expect(parseDuration('2h', 'm')).toBe(2 * 60);
18
+ });
19
+
20
+ it('should convert duration to different units', () => {
21
+ expect(parseDuration('1d', 'h')).toBe(24);
22
+ expect(parseDuration('1w', 'd')).toBe(7);
23
+ expect(parseDuration('1M', 'm')).toBe(30 * 24 * 60);
24
+ expect(parseDuration('1y', 'd')).toBe(365);
25
+ });
26
+
27
+ it('should throw error for invalid duration', () => {
28
+ // @ts-expect-error testing invalid input
29
+ expect(() => parseDuration('1x')).toThrow('invalid_unit');
30
+ });
31
+
32
+ it('should throw error for invalid conversion unit', () => {
33
+ // @ts-expect-error testing invalid input
34
+ expect(() => parseDuration('1h', 'x')).toThrow('invalid_unit');
35
+ });
36
+
37
+ it('should throw error for non-numeric duration', () => {
38
+ // @ts-expect-error testing invalid input
39
+ expect(() => parseDuration('xh')).toThrow('not_a_number');
40
+ });
41
+ });