@suzukihayate/humanun 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hayate Suzuki (鈴木颯)
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,46 @@
1
+ # humanun
2
+
3
+ Format **and** parse human-friendly **bytes**, **durations** and **numbers** — round-trippable, zero dependencies.
4
+
5
+ Most libraries only format (number → string). `humanun` goes both ways, so `parse(format(x))` gives you back `x` for clean values.
6
+
7
+ - Zero dependencies, typed (TypeScript), ESM — Node / Deno / Bun / browser
8
+ - Bytes (SI or binary), durations, compact numbers
9
+
10
+ ## Install
11
+ ```bash
12
+ npm install @suzukihayate/humanun
13
+ ```
14
+
15
+ ## Usage
16
+ ```js
17
+ import { bytes, parseBytes, duration, parseDuration, number, parseNumber } from '@suzukihayate/humanun';
18
+
19
+ bytes(1500); // "1.5 kB"
20
+ bytes(1572864, { binary: true }); // "1.5 MiB"
21
+ parseBytes('1.5 MB'); // 1500000
22
+ parseBytes('1536 KiB'); // 1572864
23
+
24
+ duration(5400000); // "1h 30m"
25
+ parseDuration('1h30m'); // 5400000
26
+ parseDuration('2.5h'); // 9000000
27
+
28
+ number(1500); // "1.5K"
29
+ parseNumber('2.3M'); // 2300000
30
+ parseNumber('1,500'); // 1500
31
+ ```
32
+
33
+ ## API
34
+ - `bytes(n, { binary?, decimals?, space? })` / `parseBytes(str)`
35
+ - `duration(ms, { parts? })` / `parseDuration(str)` (units: ms, s, m, h, d, w)
36
+ - `number(n, { decimals? })` / `parseNumber(str)` (K, M, B, T)
37
+
38
+ `parseBytes` understands both SI (`kB`, `MB`) and binary (`KiB`, `MiB`) suffixes, so parsing is always unambiguous.
39
+
40
+ ## Test
41
+ ```bash
42
+ node --test
43
+ ```
44
+
45
+ ## License
46
+ MIT © 2026 Hayate Suzuki
package/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export function bytes(n: number, opts?: { binary?: boolean; decimals?: number; space?: boolean }): string;
2
+ export function parseBytes(str: string): number;
3
+ export function duration(ms: number, opts?: { parts?: number }): string;
4
+ export function parseDuration(str: string): number;
5
+ export function number(n: number, opts?: { decimals?: number }): string;
6
+ export function parseNumber(str: string): number;
7
+ declare const _default: {
8
+ bytes: typeof bytes; parseBytes: typeof parseBytes;
9
+ duration: typeof duration; parseDuration: typeof parseDuration;
10
+ number: typeof number; parseNumber: typeof parseNumber;
11
+ };
12
+ export default _default;
package/index.js ADDED
@@ -0,0 +1,111 @@
1
+ // humanun — Format AND parse human-friendly bytes, durations and numbers.
2
+ // Round-trippable: parse(format(x)) === x for clean values.
3
+ // Zero dependencies.
4
+
5
+ /* ----------------------------- bytes ----------------------------- */
6
+ const SI = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB'];
7
+ const IEC = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];
8
+
9
+ /**
10
+ * Format a byte count into a human-readable string.
11
+ * @param {number} n bytes
12
+ * @param {{ binary?: boolean, decimals?: number, space?: boolean }} [opts]
13
+ * binary: use 1024 + IEC units (KiB...). decimals: max fraction digits (default 2).
14
+ */
15
+ export function bytes(n, opts = {}) {
16
+ const { binary = false, decimals = 2, space = true } = opts;
17
+ const base = binary ? 1024 : 1000;
18
+ const units = binary ? IEC : SI;
19
+ const sign = n < 0 ? '-' : '';
20
+ let v = Math.abs(n);
21
+ let i = 0;
22
+ while (v >= base && i < units.length - 1) { v /= base; i++; }
23
+ const num = i === 0 ? String(v) : trimNum(v.toFixed(decimals));
24
+ return `${sign}${num}${space ? ' ' : ''}${units[i]}`;
25
+ }
26
+
27
+ const BYTE_UNITS = {
28
+ b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, pb: 1e15, eb: 1e18,
29
+ kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4, pib: 1024 ** 5, eib: 1024 ** 6,
30
+ };
31
+
32
+ /** Parse "1.5 MB" / "1536KiB" / "1024" into a number of bytes. */
33
+ export function parseBytes(str) {
34
+ const m = String(str).trim().match(/^(-?\d+(?:\.\d+)?)\s*([a-zA-Z]+)?$/);
35
+ if (!m) throw new Error(`humanun: cannot parse bytes: "${str}"`);
36
+ const mult = m[2] ? BYTE_UNITS[m[2].toLowerCase()] : 1;
37
+ if (mult === undefined) throw new Error(`humanun: unknown byte unit: "${m[2]}"`);
38
+ return Math.round(parseFloat(m[1]) * mult);
39
+ }
40
+
41
+ /* ---------------------------- duration --------------------------- */
42
+ const DUR = [
43
+ ['w', 604800000], ['d', 86400000], ['h', 3600000], ['m', 60000], ['s', 1000], ['ms', 1],
44
+ ];
45
+
46
+ /**
47
+ * Format a millisecond duration into "1h 30m" style.
48
+ * @param {number} ms
49
+ * @param {{ parts?: number }} [opts] parts: max number of units to show (default 2).
50
+ */
51
+ export function duration(ms, opts = {}) {
52
+ const { parts = 2 } = opts;
53
+ let rem = Math.abs(Math.round(ms));
54
+ const sign = ms < 0 ? '-' : '';
55
+ if (rem === 0) return '0ms';
56
+ const out = [];
57
+ for (const [unit, size] of DUR) {
58
+ if (rem >= size && out.length < parts) {
59
+ const q = Math.floor(rem / size);
60
+ rem -= q * size;
61
+ out.push(`${q}${unit}`);
62
+ }
63
+ }
64
+ return sign + out.join(' ');
65
+ }
66
+
67
+ const DUR_UNITS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, hr: 3600000, d: 86400000, w: 604800000 };
68
+
69
+ /** Parse "1h30m" / "90m" / "2.5h" / "500ms" into milliseconds. */
70
+ export function parseDuration(str) {
71
+ const s = String(str).trim();
72
+ if (/^-?\d+(\.\d+)?$/.test(s)) return Math.round(parseFloat(s)); // bare number = ms
73
+ const re = /(-?\d+(?:\.\d+)?)\s*(ms|min|hr|[smhdw])/gi;
74
+ let total = 0, matched = false, m;
75
+ while ((m = re.exec(s)) !== null) {
76
+ matched = true;
77
+ total += parseFloat(m[1]) * DUR_UNITS[m[2].toLowerCase()];
78
+ }
79
+ if (!matched) throw new Error(`humanun: cannot parse duration: "${str}"`);
80
+ return Math.round(total);
81
+ }
82
+
83
+ /* ---------------------------- numbers ---------------------------- */
84
+ const NUM = [['T', 1e12], ['B', 1e9], ['M', 1e6], ['K', 1e3]];
85
+
86
+ /** Format a number compactly: 1500 -> "1.5K". */
87
+ export function number(n, opts = {}) {
88
+ const { decimals = 1 } = opts;
89
+ const sign = n < 0 ? '-' : '';
90
+ const v = Math.abs(n);
91
+ for (const [suffix, size] of NUM) {
92
+ if (v >= size) return `${sign}${trimNum((v / size).toFixed(decimals))}${suffix}`;
93
+ }
94
+ return `${sign}${v}`;
95
+ }
96
+
97
+ const NUM_UNITS = { k: 1e3, m: 1e6, b: 1e9, t: 1e12 };
98
+
99
+ /** Parse "1.5K" / "2.3M" / "1,500" into a number. */
100
+ export function parseNumber(str) {
101
+ const s = String(str).trim().replace(/,/g, '');
102
+ const m = s.match(/^(-?\d+(?:\.\d+)?)\s*([kmbtKMBT])?$/);
103
+ if (!m) throw new Error(`humanun: cannot parse number: "${str}"`);
104
+ const mult = m[2] ? NUM_UNITS[m[2].toLowerCase()] : 1;
105
+ return parseFloat(m[1]) * mult;
106
+ }
107
+
108
+ /* ----------------------------- utils ----------------------------- */
109
+ function trimNum(s) { return s.replace(/\.0+$/, '').replace(/(\.\d*?)0+$/, '$1'); }
110
+
111
+ export default { bytes, parseBytes, duration, parseDuration, number, parseNumber };
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@suzukihayate/humanun",
3
+ "version": "0.1.0",
4
+ "description": "Format AND parse human-friendly bytes, durations and numbers. Round-trippable, zero dependencies.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "types": "index.d.ts",
8
+ "exports": { ".": { "types": "./index.d.ts", "default": "./index.js" } },
9
+ "files": ["index.js", "index.d.ts", "README.md", "LICENSE"],
10
+ "scripts": { "test": "node --test" },
11
+ "keywords": ["humanize", "bytes", "filesize", "duration", "ms", "pretty", "format", "parse", "zero-dependency"],
12
+ "repository": { "type": "git", "url": "git+https://github.com/HaYaTedonn/humanun.git" },
13
+ "author": "Hayate Suzuki",
14
+ "license": "MIT",
15
+ "engines": { "node": ">=18" },
16
+ "sideEffects": false
17
+ }