@mrmartineau/kit 0.1.0 → 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.
Files changed (37) hide show
  1. package/README.md +69 -1
  2. package/package.json +14 -8
  3. package/src/index.ts +1 -0
  4. package/src/utils/formatters/constants.ts +1 -0
  5. package/src/utils/formatters/index.ts +24 -0
  6. package/src/utils/formatters/numbers/__tests__/formatNumberBase.test.ts +68 -0
  7. package/src/utils/formatters/numbers/__tests__/formatNumberCurrency.test.ts +56 -0
  8. package/src/utils/formatters/numbers/__tests__/formatNumberDecimal.test.ts +76 -0
  9. package/src/utils/formatters/numbers/__tests__/formatNumberDecimalForceDecimalPlaces.test.ts +40 -0
  10. package/src/utils/formatters/numbers/formatNumberAccounting.ts +27 -0
  11. package/src/utils/formatters/numbers/formatNumberBase.ts +21 -0
  12. package/src/utils/formatters/numbers/formatNumberBytes.ts +29 -0
  13. package/src/utils/formatters/numbers/formatNumberCompact.ts +19 -0
  14. package/src/utils/formatters/numbers/formatNumberCurrency.ts +25 -0
  15. package/src/utils/formatters/numbers/formatNumberDecimal.ts +21 -0
  16. package/src/utils/formatters/numbers/formatNumberDecimalForceDecimalPlaces.ts +23 -0
  17. package/src/utils/formatters/numbers/formatNumberOrdinal.ts +25 -0
  18. package/src/utils/formatters/numbers/formatNumberPercent.ts +21 -0
  19. package/src/utils/formatters/numbers/formatNumberRange.ts +22 -0
  20. package/src/utils/formatters/numbers/formatNumberSignDisplay.ts +24 -0
  21. package/src/utils/formatters/strings/formatInitials.ts +17 -0
  22. package/src/utils/formatters/strings/formatList.test.ts +51 -0
  23. package/src/utils/formatters/strings/formatList.ts +10 -0
  24. package/src/utils/formatters/strings/maskString.ts +30 -0
  25. package/src/utils/formatters/strings/normalizeWhitespace.ts +8 -0
  26. package/src/utils/formatters/strings/pluralize.ts +15 -0
  27. package/src/utils/formatters/strings/slugify.ts +12 -0
  28. package/src/utils/formatters/strings/splitWords.ts +12 -0
  29. package/src/utils/formatters/strings/stripDiacritics.ts +7 -0
  30. package/src/utils/formatters/strings/toCamelCase.ts +17 -0
  31. package/src/utils/formatters/strings/toKebabCase.ts +11 -0
  32. package/src/utils/formatters/strings/toPascalCase.ts +14 -0
  33. package/src/utils/formatters/strings/toSnakeCase.ts +11 -0
  34. package/src/utils/formatters/strings/toStartCase.test.ts +45 -0
  35. package/src/utils/formatters/strings/toStartCase.ts +21 -0
  36. package/src/utils/formatters/strings/truncate.ts +29 -0
  37. package/src/utils/index.ts +1 -0
package/README.md CHANGED
@@ -85,7 +85,7 @@ In your project's `biome.json`:
85
85
  ```json
86
86
  {
87
87
  "$schema": "https://biomejs.dev/schemas/2.1.3/schema.json",
88
- "extends": ["@mrmartineau/kit/biome"]
88
+ "extends": ["./node_modules/@mrmartineau/kit/src/biome/biome.json"]
89
89
  }
90
90
  ```
91
91
 
@@ -160,6 +160,74 @@ import { ... } from "@mrmartineau/kit/components";
160
160
  import { ... } from "@mrmartineau/kit/hooks";
161
161
  ```
162
162
 
163
+ #### Formatters
164
+
165
+ A collection of number and string formatters. All number formatters wrap
166
+ `Intl.NumberFormat` and default to the `en-GB` locale.
167
+
168
+ ```ts
169
+ import {
170
+ formatNumberAccounting,
171
+ formatNumberBase,
172
+ formatNumberBytes,
173
+ formatNumberCompact,
174
+ formatNumberCurrency,
175
+ formatNumberDecimal,
176
+ formatNumberDecimalForceDecimalPlaces,
177
+ formatNumberOrdinal,
178
+ formatNumberPercent,
179
+ formatNumberRange,
180
+ formatNumberSignDisplay,
181
+ formatInitials,
182
+ formatList,
183
+ maskString,
184
+ normalizeWhitespace,
185
+ pluralize,
186
+ slugify,
187
+ stripDiacritics,
188
+ toCamelCase,
189
+ toKebabCase,
190
+ toPascalCase,
191
+ toSnakeCase,
192
+ toStartCase,
193
+ truncate,
194
+ } from '@mrmartineau/kit/utils'
195
+ ```
196
+
197
+ ##### Number formatters
198
+
199
+ | Function | Signature | Example |
200
+ | --------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
201
+ | `formatNumberBase` | `(value, options?)` | `formatNumberBase(1234)` → `"1,234"` |
202
+ | `formatNumberDecimal` | `(value, decimalCount = 2, options?)` | `formatNumberDecimal(1234.567, 2)` → `"1,234.57"` |
203
+ | `formatNumberDecimalForceDecimalPlaces` | `(value, decimalCount = 2, options?)` | `formatNumberDecimalForceDecimalPlaces(10, 2)` → `"10.00"` |
204
+ | `formatNumberCurrency` | `(value, currency, decimalCount = 2, options?)` | `formatNumberCurrency(1234, "GBP")` → `"£1,234.00"` |
205
+ | `formatNumberAccounting` | `(value, currency, decimalCount = 2, options?)` — negatives wrapped in parens | `formatNumberAccounting(-100, "USD")` → `"($100.00)"` |
206
+ | `formatNumberPercent` | `(value, decimalCount = 2, options?)` — value already in decimal form (`0.42` → `42%`) | `formatNumberPercent(0.421)` → `"42.1%"` |
207
+ | `formatNumberCompact` | `(value, display = "short", options?)` | `formatNumberCompact(1200)` → `"1.2K"` |
208
+ | `formatNumberOrdinal` | `(value, locale = "en-GB")` | `formatNumberOrdinal(3)` → `"3rd"` |
209
+ | `formatNumberBytes` | `(bytes, binary = false, decimalCount = 2)` | `formatNumberBytes(1536, true)` → `"1.5 KiB"` |
210
+ | `formatNumberRange` | `(min, max, options?, locale = "en-GB")` | `formatNumberRange(1, 5)` → `"1–5"` |
211
+ | `formatNumberSignDisplay` | `(value, decimalCount = 2, signDisplay = "exceptZero", options?)` | `formatNumberSignDisplay(5)` → `"+5"` |
212
+
213
+ ##### String formatters
214
+
215
+ | Function | Signature | Example |
216
+ | --------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------ |
217
+ | `formatList` | `(array, options?)` — wraps `Intl.ListFormat` | `formatList(["a","b","c"])` → `"a, b, and c"` |
218
+ | `toStartCase` | `(str)` | `toStartCase("hello_world")` → `"Hello World"` |
219
+ | `toCamelCase` | `(str)` | `toCamelCase("hello_world")` → `"helloWorld"` |
220
+ | `toPascalCase` | `(str)` | `toPascalCase("hello_world")` → `"HelloWorld"` |
221
+ | `toKebabCase` | `(str)` | `toKebabCase("helloWorld")` → `"hello-world"` |
222
+ | `toSnakeCase` | `(str)` | `toSnakeCase("helloWorld")` → `"hello_world"` |
223
+ | `truncate` | `(str, maxLength, { ellipsis = "…", wordBoundary = false }?)` | `truncate("Hello world", 8)` → `"Hello w…"` |
224
+ | `slugify` | `(str)` | `slugify("Hello, World!")` → `"hello-world"` |
225
+ | `pluralize` | `(count, singular, plural?)` | `pluralize(2, "child", "children")` → `"children"` |
226
+ | `stripDiacritics` | `(str)` | `stripDiacritics("café")` → `"cafe"` |
227
+ | `normalizeWhitespace` | `(str)` | `normalizeWhitespace(" a\n\tb ")` → `"a b"` |
228
+ | `maskString` | `(str, { visibleStart = 0, visibleEnd = 4, maskChar = "•" }?)` | `maskString("4242424242424242")` → `"••••••••••••4242"` |
229
+ | `formatInitials` | `(name, maxLength = 2)` | `formatInitials("John Smith")` → `"JS"` |
230
+
163
231
  ## Exports map
164
232
 
165
233
  | Specifier | Resolves to |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrmartineau/kit",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -22,22 +22,28 @@
22
22
  "src"
23
23
  ],
24
24
  "devDependencies": {
25
- "@types/bun": "latest",
26
- "@types/eslint": "^9.6.1"
25
+ "@semantic-release/changelog": "^6.0.3",
26
+ "@semantic-release/commit-analyzer": "^13.0.1",
27
+ "@semantic-release/git": "^10.0.1",
28
+ "@semantic-release/github": "^12.0.8",
29
+ "@semantic-release/npm": "^13.1.5",
30
+ "@semantic-release/release-notes-generator": "^14.1.1",
31
+ "@types/bun": "1.3.14",
32
+ "@types/eslint": "^9.6.1",
33
+ "semantic-release": "^25.0.3"
27
34
  },
28
35
  "peerDependencies": {
29
36
  "eslint": "",
30
- "typescript": "^5"
37
+ "typescript": "^6.0.3"
31
38
  },
32
39
  "peerDependenciesMeta": {
33
40
  "eslint": {
34
41
  "optional": true
35
42
  }
36
43
  },
37
- "dependencies": {
38
- "release-it": "^19.2.4"
39
- },
40
44
  "scripts": {
41
- "release": "release-it"
45
+ "test": "bun test",
46
+ "typecheck": "tsc --noEmit",
47
+ "release": "semantic-release"
42
48
  }
43
49
  }
package/src/index.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from "./sounds/index.ts";
2
+ export * from './utils/index.js';
@@ -0,0 +1 @@
1
+ export const DEFAULT_DECIMAL_PLACES = 2;
@@ -0,0 +1,24 @@
1
+ export { formatNumberAccounting } from "./numbers/formatNumberAccounting.js";
2
+ export { formatNumberBase } from "./numbers/formatNumberBase.js";
3
+ export { formatNumberBytes } from "./numbers/formatNumberBytes.js";
4
+ export { formatNumberCompact } from "./numbers/formatNumberCompact.js";
5
+ export { formatNumberCurrency } from "./numbers/formatNumberCurrency.js";
6
+ export { formatNumberDecimal } from "./numbers/formatNumberDecimal.js";
7
+ export { formatNumberDecimalForceDecimalPlaces } from "./numbers/formatNumberDecimalForceDecimalPlaces.js";
8
+ export { formatNumberOrdinal } from "./numbers/formatNumberOrdinal.js";
9
+ export { formatNumberPercent } from "./numbers/formatNumberPercent.js";
10
+ export { formatNumberRange } from "./numbers/formatNumberRange.js";
11
+ export { formatNumberSignDisplay } from "./numbers/formatNumberSignDisplay.js";
12
+ export { formatInitials } from "./strings/formatInitials.js";
13
+ export { formatList } from "./strings/formatList.js";
14
+ export { maskString } from "./strings/maskString.js";
15
+ export { normalizeWhitespace } from "./strings/normalizeWhitespace.js";
16
+ export { pluralize } from "./strings/pluralize.js";
17
+ export { slugify } from "./strings/slugify.js";
18
+ export { stripDiacritics } from "./strings/stripDiacritics.js";
19
+ export { toCamelCase } from "./strings/toCamelCase.js";
20
+ export { toKebabCase } from "./strings/toKebabCase.js";
21
+ export { toPascalCase } from "./strings/toPascalCase.js";
22
+ export { toSnakeCase } from "./strings/toSnakeCase.js";
23
+ export { toStartCase } from "./strings/toStartCase.js";
24
+ export { truncate } from "./strings/truncate.js";
@@ -0,0 +1,68 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { formatNumberBase } from "../formatNumberBase.js";
4
+
5
+ describe("formatNumberBase", () => {
6
+ it("should throw if no value provided", () => {
7
+ // @ts-expect-error - Testing for invalid input
8
+ expect(() => formatNumberBase()).toThrowError(
9
+ "formatNumber: Value is not defined",
10
+ );
11
+ // @ts-expect-error - Testing for invalid input
12
+ expect(() => formatNumberBase(undefined)).toThrowError(
13
+ "formatNumber: Value is not defined",
14
+ ); // @ts-expect-error - Testing for invalid input
15
+ expect(() => formatNumberBase(null)).toThrowError(
16
+ "formatNumber: Value is not defined",
17
+ );
18
+ });
19
+
20
+ it("should throw if value is invalid", () => {
21
+ // @ts-expect-error - Testing for invalid input
22
+ expect(() => formatNumberBase(false)).toThrowError(
23
+ "formatNumber: Invalid number format",
24
+ );
25
+ // @ts-expect-error - Testing for invalid input
26
+ expect(() => formatNumberBase([false])).toThrowError(
27
+ "formatNumber: Invalid number format",
28
+ );
29
+ });
30
+
31
+ it("should throw if string passed is invalid", () => {
32
+ expect(() => formatNumberBase("-")).toThrowError(
33
+ "formatNumber: Invalid number format",
34
+ );
35
+ });
36
+
37
+ it("should used the Intl.NumberFormat defaults and format a number to the default number of decimal places (3) when no options are passed", () => {
38
+ expect(formatNumberBase(123456.789456456)).toBe("123,456.789");
39
+ expect(formatNumberBase(0.0)).toBe("0");
40
+ });
41
+
42
+ it("should used the Intl.NumberFormat defaults and format a number to the default number of decimal places (3) when an empty options object is passed", () => {
43
+ expect(formatNumberBase(123456.789456456, {})).toBe("123,456.789");
44
+ expect(formatNumberBase(0, {})).toBe("0");
45
+ });
46
+
47
+ it("should format a number to 0 decimal places", () => {
48
+ expect(
49
+ formatNumberBase(123456.789, {
50
+ maximumFractionDigits: 0,
51
+ }),
52
+ ).toBe("123,457");
53
+ expect(
54
+ formatNumberBase(0, {
55
+ maximumFractionDigits: 0,
56
+ }),
57
+ ).toBe("0");
58
+ });
59
+
60
+ it("should format a number based on the options passed", () => {
61
+ expect(
62
+ formatNumberBase(123456.789, {
63
+ style: "currency",
64
+ currency: "EUR",
65
+ }),
66
+ ).toBe("€123,456.79");
67
+ });
68
+ });
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { formatNumberCurrency } from "../formatNumberCurrency.js";
4
+
5
+ describe("formatNumberCurrency", () => {
6
+ it("should format a number to GBP currency", () => {
7
+ expect(formatNumberCurrency(1.789, "GBP")).toBe("£1.79");
8
+ expect(formatNumberCurrency(12.789, "GBP")).toBe("£12.79");
9
+ expect(formatNumberCurrency(123.789, "GBP")).toBe("£123.79");
10
+ });
11
+
12
+ it("should format a number to USD currency", () => {
13
+ expect(formatNumberCurrency(1.789, "USD")).toBe("$1.79");
14
+ expect(formatNumberCurrency(12.789, "USD")).toBe("$12.79");
15
+ expect(formatNumberCurrency(123.789, "USD")).toBe("$123.79");
16
+ });
17
+
18
+ it("should format a number to USD currency with specific number of decimal places", () => {
19
+ expect(formatNumberCurrency(1.789, "USD", 1)).toBe("$1.8");
20
+ expect(formatNumberCurrency(12.789, "USD", 2)).toBe("$12.79");
21
+ expect(formatNumberCurrency(123.789, "USD", 5)).toBe("$123.789");
22
+ });
23
+
24
+ it("should format a number to GBP currency with custom number format options", () => {
25
+ expect(
26
+ formatNumberCurrency(1.789, "GBP", undefined, {
27
+ maximumFractionDigits: 1,
28
+ }),
29
+ ).toBe("£1.8");
30
+ expect(
31
+ formatNumberCurrency(12.789, "GBP", undefined, {
32
+ maximumFractionDigits: 1,
33
+ }),
34
+ ).toBe("£12.8");
35
+ expect(
36
+ formatNumberCurrency(123.789, "GBP", undefined, {
37
+ maximumFractionDigits: 1,
38
+ }),
39
+ ).toBe("£123.8");
40
+ });
41
+
42
+ it("should throw if passing an invalid value", () => {
43
+ expect(() => formatNumberCurrency("-", "GBP")).toThrowError(
44
+ "formatNumber: Invalid number format",
45
+ );
46
+ });
47
+
48
+ it("should throw if passing an invalid currency code", () => {
49
+ expect(() => formatNumberCurrency(1.789, "DARE")).toThrowError();
50
+ });
51
+
52
+ it("should throw if missing a currency code", () => {
53
+ // @ts-expect-error - Testing for invalid input
54
+ expect(() => formatNumberCurrency(1.789)).toThrowError();
55
+ });
56
+ });
@@ -0,0 +1,76 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { formatNumberDecimal } from "../formatNumberDecimal.js";
4
+
5
+ describe("formatNumberDecimal", () => {
6
+ it("should throw if no value provided", () => {
7
+ // @ts-expect-error - Testing for invalid input
8
+ expect(() => formatNumberDecimal()).toThrowError(
9
+ "formatNumber: Value is not defined",
10
+ );
11
+ // @ts-expect-error - Testing for invalid input
12
+ expect(() => formatNumberDecimal(undefined)).toThrowError(
13
+ "formatNumber: Value is not defined",
14
+ );
15
+ // @ts-expect-error - Testing for invalid input
16
+ expect(() => formatNumberDecimal(null)).toThrowError(
17
+ "formatNumber: Value is not defined",
18
+ );
19
+ });
20
+
21
+ it("should throw if value is invalid", () => {
22
+ // @ts-expect-error - Testing for invalid input
23
+ expect(() => formatNumberDecimal(false)).toThrowError(
24
+ "formatNumber: Invalid number format",
25
+ );
26
+ // @ts-expect-error - Testing for invalid input
27
+ expect(() => formatNumberDecimal([false])).toThrowError(
28
+ "formatNumber: Invalid number format",
29
+ );
30
+ });
31
+
32
+ it("should throw if string passed is invalid", () => {
33
+ expect(() => formatNumberDecimal("-")).toThrowError(
34
+ "formatNumber: Invalid number format",
35
+ );
36
+ });
37
+
38
+ it("should format a number to the default number of decimal places (2)", () => {
39
+ expect(formatNumberDecimal(123456.789)).toBe("123,456.79");
40
+ expect(formatNumberDecimal(0)).toBe("0");
41
+ });
42
+
43
+ it("should format a number to 0 decimal places", () => {
44
+ expect(formatNumberDecimal(123456.789, 0)).toBe("123,457");
45
+ expect(formatNumberDecimal(0, 0)).toBe("0");
46
+ });
47
+
48
+ it("should format a number to 1 decimal place", () => {
49
+ expect(formatNumberDecimal(123456.789, 1)).toBe("123,456.8");
50
+ });
51
+
52
+ it("should format a number to 2 decimal places", () => {
53
+ expect(formatNumberDecimal(123456.789, 2)).toBe("123,456.79");
54
+ expect(formatNumberDecimal(0.1, 2)).toBe("0.1");
55
+ });
56
+
57
+ it("should format a number to 3 decimal places", () => {
58
+ expect(formatNumberDecimal(123456.789, 3)).toBe("123,456.789");
59
+ });
60
+
61
+ it("should format a number to 4 decimal places", () => {
62
+ expect(formatNumberDecimal(123456.789, 4)).toBe("123,456.789");
63
+ });
64
+
65
+ it("should format non-standard numbers", () => {
66
+ expect(formatNumberDecimal(6.938893903907228e-18, 2)).toBe("0");
67
+ });
68
+
69
+ it("should format with custom number format options", () => {
70
+ expect(
71
+ formatNumberDecimal(1.789, 3, {
72
+ maximumFractionDigits: 1, // this will override the decimalCount parameter
73
+ }),
74
+ ).toBe("1.8");
75
+ });
76
+ });
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { formatNumberDecimalForceDecimalPlaces } from "../formatNumberDecimalForceDecimalPlaces.js";
4
+
5
+ describe("formattedNumberDecimalForceDecimalPlaces", () => {
6
+ it("should format a number to 1 decimal place", () => {
7
+ expect(formatNumberDecimalForceDecimalPlaces(123456.789, 1)).toBe(
8
+ "123,456.8",
9
+ );
10
+ });
11
+
12
+ it("should format a number to 2 decimal places", () => {
13
+ expect(formatNumberDecimalForceDecimalPlaces(123456.789, 2)).toBe(
14
+ "123,456.79",
15
+ );
16
+ expect(formatNumberDecimalForceDecimalPlaces(0.1, 2)).toBe("0.10");
17
+ });
18
+
19
+ it("should format a number to 3 decimal places", () => {
20
+ expect(formatNumberDecimalForceDecimalPlaces(123456.789, 3)).toBe(
21
+ "123,456.789",
22
+ );
23
+ });
24
+
25
+ it("should format a number to 4 decimal places", () => {
26
+ expect(formatNumberDecimalForceDecimalPlaces(123456.789, 4)).toBe(
27
+ "123,456.7890",
28
+ );
29
+ });
30
+
31
+ it("should format non-standard numbers", () => {
32
+ expect(
33
+ formatNumberDecimalForceDecimalPlaces(6.938893903907228e-18, 2),
34
+ ).toBe("0.00");
35
+ });
36
+
37
+ it("should format with custom number format options", () => {
38
+ expect(formatNumberDecimalForceDecimalPlaces(1.789, 3)).toBe("1.789");
39
+ });
40
+ });
@@ -0,0 +1,27 @@
1
+ import { DEFAULT_DECIMAL_PLACES } from "../constants.js";
2
+ import { formatNumberBase } from "./formatNumberBase.js";
3
+
4
+ /**
5
+ * Formats a number as currency in accounting style: negative values are wrapped
6
+ * in parentheses (e.g. `-100` → `(£100.00)`).
7
+ * @param value - The number to format.
8
+ * @param currency - The currency code e.g. `USD`, `GBP`, `EUR`.
9
+ * @param decimalCount - Number of decimal places. Default 2.
10
+ * @param options - Additional, optional `Intl.NumberFormatOptions`.
11
+ */
12
+ export const formatNumberAccounting = (
13
+ value: number | string,
14
+ currency: string,
15
+ decimalCount: number = DEFAULT_DECIMAL_PLACES,
16
+ options?: Intl.NumberFormatOptions,
17
+ ) => {
18
+ return formatNumberBase(value, {
19
+ minimumFractionDigits: decimalCount,
20
+ maximumFractionDigits: decimalCount,
21
+ ...options,
22
+ style: "currency",
23
+ currency,
24
+ currencyDisplay: "narrowSymbol",
25
+ currencySign: "accounting",
26
+ });
27
+ };
@@ -0,0 +1,21 @@
1
+ export const formatNumberBase = (
2
+ value: string | number,
3
+ options?: Intl.NumberFormatOptions,
4
+ ): string => {
5
+ if (value == undefined || value === "" || value === null) {
6
+ throw TypeError("formatNumber: Value is not defined");
7
+ }
8
+ if (typeof value === "boolean" || typeof value === "object") {
9
+ throw Error("formatNumber: Invalid number format");
10
+ }
11
+
12
+ if (typeof value === "string") {
13
+ const trimmed = value.trim();
14
+ value = trimmed === "" ? NaN : Number(trimmed);
15
+ if (isNaN(value)) {
16
+ throw new Error("formatNumber: Invalid number format");
17
+ }
18
+ }
19
+
20
+ return new Intl.NumberFormat("en-GB", options).format(value);
21
+ };
@@ -0,0 +1,29 @@
1
+ import { DEFAULT_DECIMAL_PLACES } from "../constants.js";
2
+ import { formatNumberDecimal } from "./formatNumberDecimal.js";
3
+
4
+ const DECIMAL_UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB"] as const;
5
+ const BINARY_UNITS = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"] as const;
6
+
7
+ /**
8
+ * Formats a byte count as a human-readable string (e.g. `1500` → `1.5 KB`).
9
+ * @param bytes - The byte count.
10
+ * @param binary - If `true`, use 1024-based units (KiB, MiB, …). Default `false`.
11
+ * @param decimalCount - Maximum decimal places. Default 2.
12
+ */
13
+ export const formatNumberBytes = (
14
+ bytes: number,
15
+ binary: boolean = false,
16
+ decimalCount: number = DEFAULT_DECIMAL_PLACES,
17
+ ) => {
18
+ if (!Number.isFinite(bytes)) {
19
+ throw new Error("formatNumberBytes: Invalid byte count");
20
+ }
21
+ if (bytes === 0) return "0 B";
22
+
23
+ const base = binary ? 1024 : 1000;
24
+ const units = binary ? BINARY_UNITS : DECIMAL_UNITS;
25
+ const rawExponent = Math.floor(Math.log(Math.abs(bytes)) / Math.log(base));
26
+ const exponent = Math.min(Math.max(rawExponent, 0), units.length - 1);
27
+ const value = bytes / Math.pow(base, exponent);
28
+ return `${formatNumberDecimal(value, decimalCount)} ${units[exponent]}`;
29
+ };
@@ -0,0 +1,19 @@
1
+ import { formatNumberBase } from "./formatNumberBase.js";
2
+
3
+ /**
4
+ * Formats a number in compact notation (e.g. `1200` → `1.2K`).
5
+ * @param value - The number to format.
6
+ * @param display - `"short"` (default) or `"long"` (e.g. `1.2 thousand`).
7
+ * @param options - Additional, optional `Intl.NumberFormatOptions`.
8
+ */
9
+ export const formatNumberCompact = (
10
+ value: number | string,
11
+ display: "short" | "long" = "short",
12
+ options?: Intl.NumberFormatOptions,
13
+ ) => {
14
+ return formatNumberBase(value, {
15
+ notation: "compact",
16
+ compactDisplay: display,
17
+ ...options,
18
+ });
19
+ };
@@ -0,0 +1,25 @@
1
+ import { DEFAULT_DECIMAL_PLACES } from "../constants.js";
2
+ import { formatNumberBase } from "./formatNumberBase.js";
3
+
4
+ /**
5
+ * Formats a number as currency.
6
+ * @param value - The number to format.
7
+ * @param currency - The currency code e.g. USD, GBP, EUR, etc.
8
+ * @param decimalCount - Optional. The number of decimal places to display. Default is 2.
9
+ * @param options - Additional, optional options for formatting the number.
10
+ * @returns The formatted currency as a string.
11
+ */
12
+ export const formatNumberCurrency = (
13
+ value: number | string,
14
+ currency: string,
15
+ decimalCount: number = DEFAULT_DECIMAL_PLACES,
16
+ options?: Intl.NumberFormatOptions,
17
+ ) => {
18
+ return formatNumberBase(value, {
19
+ maximumFractionDigits: decimalCount,
20
+ ...options,
21
+ style: "currency",
22
+ currencyDisplay: "narrowSymbol",
23
+ currency,
24
+ });
25
+ };
@@ -0,0 +1,21 @@
1
+ import { DEFAULT_DECIMAL_PLACES } from "../constants.js";
2
+ import { formatNumberBase } from "./formatNumberBase.js";
3
+
4
+ /**
5
+ * Formats a number with decimal places.
6
+ * @param value - The number to format.
7
+ * @param decimalCount - Optional. The number of decimal places to display. Default is 2.
8
+ * @param options - Additional, optional options for formatting the number.
9
+ * @returns The formatted number as a string.
10
+ */
11
+ export const formatNumberDecimal = (
12
+ value: number | string,
13
+ decimalCount: number = DEFAULT_DECIMAL_PLACES,
14
+ options?: Intl.NumberFormatOptions,
15
+ ) => {
16
+ return formatNumberBase(value, {
17
+ style: "decimal",
18
+ maximumFractionDigits: decimalCount,
19
+ ...options,
20
+ });
21
+ };
@@ -0,0 +1,23 @@
1
+ import { DEFAULT_DECIMAL_PLACES } from "../constants.js";
2
+ import { formatNumberDecimal } from "./formatNumberDecimal.js";
3
+
4
+ /**
5
+ * Formats a number with decimal places.
6
+ * @param value - The number to format.
7
+ * @param decimalCount - The number of decimal places to display. Default is 2.
8
+ * @param options - Additional, optional options for formatting the number.
9
+ * @returns The formatted number as a string.
10
+ */
11
+ export const formatNumberDecimalForceDecimalPlaces = (
12
+ value: number,
13
+ decimalCount: number = DEFAULT_DECIMAL_PLACES,
14
+ options?: Intl.NumberFormatOptions,
15
+ ) => {
16
+ return formatNumberDecimal(value, decimalCount, {
17
+ ...options,
18
+ // The `Intl.NumberFormat` constructor that `formatNumberDecimal` uses trims
19
+ // decimal places if possible so I have ensured that the number of decimal
20
+ // places will be kept no matter what here.
21
+ minimumFractionDigits: decimalCount,
22
+ });
23
+ };
@@ -0,0 +1,25 @@
1
+ const ORDINAL_SUFFIXES: Record<Intl.LDMLPluralRule, string> = {
2
+ zero: "th",
3
+ one: "st",
4
+ two: "nd",
5
+ few: "rd",
6
+ many: "th",
7
+ other: "th",
8
+ };
9
+
10
+ /**
11
+ * Formats an integer with its English ordinal suffix (e.g. `1` → `1st`).
12
+ * @param value - The integer to format.
13
+ * @param locale - Optional. Defaults to `"en-GB"`.
14
+ */
15
+ export const formatNumberOrdinal = (
16
+ value: number,
17
+ locale: string = "en-GB",
18
+ ) => {
19
+ if (!Number.isInteger(value)) {
20
+ throw new Error("formatNumberOrdinal: Value must be an integer");
21
+ }
22
+ const rules = new Intl.PluralRules(locale, { type: "ordinal" });
23
+ const suffix = ORDINAL_SUFFIXES[rules.select(value)];
24
+ return `${value}${suffix}`;
25
+ };
@@ -0,0 +1,21 @@
1
+ import { DEFAULT_DECIMAL_PLACES } from "../constants.js";
2
+ import { formatNumberBase } from "./formatNumberBase.js";
3
+
4
+ /**
5
+ * Formats a number as a percentage. The value is expected to already be in
6
+ * decimal form (e.g. `0.42` → `42%`).
7
+ * @param value - The number to format.
8
+ * @param decimalCount - Optional. Maximum decimal places. Default 2.
9
+ * @param options - Additional, optional `Intl.NumberFormatOptions`.
10
+ */
11
+ export const formatNumberPercent = (
12
+ value: number | string,
13
+ decimalCount: number = DEFAULT_DECIMAL_PLACES,
14
+ options?: Intl.NumberFormatOptions,
15
+ ) => {
16
+ return formatNumberBase(value, {
17
+ style: "percent",
18
+ maximumFractionDigits: decimalCount,
19
+ ...options,
20
+ });
21
+ };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Formats a numeric range using `Intl.NumberFormat#formatRange`
3
+ * (e.g. `1`, `5` → `1–5`).
4
+ * @param min - Lower bound.
5
+ * @param max - Upper bound.
6
+ * @param options - Additional, optional `Intl.NumberFormatOptions`.
7
+ * @param locale - Optional. Defaults to `"en-GB"`.
8
+ */
9
+ export const formatNumberRange = (
10
+ min: number,
11
+ max: number,
12
+ options?: Intl.NumberFormatOptions,
13
+ locale: string = "en-GB",
14
+ ) => {
15
+ if (!Number.isFinite(min) || !Number.isFinite(max)) {
16
+ throw new Error("formatNumberRange: Invalid range");
17
+ }
18
+ if (min > max) {
19
+ throw new RangeError("formatNumberRange: min must be <= max");
20
+ }
21
+ return new Intl.NumberFormat(locale, options).formatRange(min, max);
22
+ };
@@ -0,0 +1,24 @@
1
+ import { DEFAULT_DECIMAL_PLACES } from "../constants.js";
2
+ import { formatNumberBase } from "./formatNumberBase.js";
3
+
4
+ /**
5
+ * Formats a number with an explicit sign for non-zero values (e.g. `5` → `+5`,
6
+ * `-5` → `-5`, `0` → `0`). Pass `signDisplay: "always"` to also sign zero.
7
+ * @param value - The number to format.
8
+ * @param decimalCount - Maximum decimal places. Default 2.
9
+ * @param signDisplay - `Intl.NumberFormatOptions['signDisplay']`. Default `"exceptZero"`.
10
+ * @param options - Additional, optional `Intl.NumberFormatOptions`.
11
+ */
12
+ export const formatNumberSignDisplay = (
13
+ value: number | string,
14
+ decimalCount: number = DEFAULT_DECIMAL_PLACES,
15
+ signDisplay: Intl.NumberFormatOptions["signDisplay"] = "exceptZero",
16
+ options?: Intl.NumberFormatOptions,
17
+ ) => {
18
+ return formatNumberBase(value, {
19
+ style: "decimal",
20
+ maximumFractionDigits: decimalCount,
21
+ signDisplay,
22
+ ...options,
23
+ });
24
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Returns the initials for a name.
3
+ * @param name - The full name string.
4
+ * @param maxLength - Maximum number of initials to return. Default 2.
5
+ * @example formatInitials("John Smith") // "JS"
6
+ * @example formatInitials("Mary Jane Watson", 3) // "MJW"
7
+ */
8
+ export function formatInitials(name: string, maxLength: number = 2): string {
9
+ if (!name) return "";
10
+ return name
11
+ .trim()
12
+ .split(/\s+/)
13
+ .map((part) => part.charAt(0).toUpperCase())
14
+ .filter(Boolean)
15
+ .slice(0, maxLength)
16
+ .join("");
17
+ }
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { formatList } from "./formatList";
4
+
5
+ describe("formatList", () => {
6
+ it("formats list with default options (long conjunction)", () => {
7
+ const input = ["apple", "banana", "orange"];
8
+ expect(formatList(input)).toBe("apple, banana, and orange");
9
+ });
10
+
11
+ it("formats list with disjunction type", () => {
12
+ const input = ["apple", "banana", "orange"];
13
+ expect(formatList(input, { type: "disjunction" })).toBe(
14
+ "apple, banana, or orange",
15
+ );
16
+ });
17
+
18
+ it("formats list with unit type", () => {
19
+ const input = ["apple", "banana", "orange"];
20
+ expect(formatList(input, { type: "unit" })).toBe("apple, banana, orange");
21
+ });
22
+
23
+ it("formats list with short style", () => {
24
+ const input = ["apple", "banana", "orange"];
25
+ expect(formatList(input, { style: "short", type: "conjunction" })).toBe(
26
+ "apple, banana, & orange",
27
+ );
28
+ });
29
+
30
+ it("formats list with narrow style", () => {
31
+ const input = ["apple", "banana", "orange"];
32
+ expect(formatList(input, { style: "narrow", type: "conjunction" })).toBe(
33
+ "apple, banana, orange",
34
+ );
35
+ });
36
+
37
+ it("handles single item list", () => {
38
+ const input = ["apple"];
39
+ expect(formatList(input)).toBe("apple");
40
+ });
41
+
42
+ it("handles two item list", () => {
43
+ const input = ["apple", "banana"];
44
+ expect(formatList(input)).toBe("apple and banana");
45
+ });
46
+
47
+ it("handles empty list", () => {
48
+ const input: string[] = [];
49
+ expect(formatList(input)).toBe("");
50
+ });
51
+ });
@@ -0,0 +1,10 @@
1
+ export function formatList(
2
+ array: Array<string>,
3
+ options: Intl.ListFormatOptions = {
4
+ style: "long",
5
+ type: "conjunction",
6
+ },
7
+ ) {
8
+ const formatter = new Intl.ListFormat("en", options);
9
+ return formatter.format(array);
10
+ }
@@ -0,0 +1,30 @@
1
+ export interface MaskStringOptions {
2
+ /** Number of characters to keep visible at the start. Default 0. */
3
+ visibleStart?: number;
4
+ /** Number of characters to keep visible at the end. Default 4. */
5
+ visibleEnd?: number;
6
+ /** Character used to mask the hidden portion. Default `"•"`. */
7
+ maskChar?: string;
8
+ }
9
+
10
+ /**
11
+ * Masks the middle of a string while keeping a configurable number of
12
+ * characters visible at each end. Useful for partially redacting secrets
13
+ * (tokens, card numbers, emails).
14
+ * @example maskString("4242424242424242", { visibleEnd: 4 }) // "••••••••••••4242"
15
+ */
16
+ export function maskString(
17
+ str: string,
18
+ options: MaskStringOptions = {},
19
+ ): string {
20
+ const { visibleStart = 0, visibleEnd = 4, maskChar = "•" } = options;
21
+ if (!str) return "";
22
+
23
+ const total = str.length;
24
+ if (visibleStart + visibleEnd >= total) return str;
25
+
26
+ const start = str.slice(0, visibleStart);
27
+ const end = visibleEnd === 0 ? "" : str.slice(-visibleEnd);
28
+ const masked = maskChar.repeat(total - visibleStart - visibleEnd);
29
+ return `${start}${masked}${end}`;
30
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Collapses any run of whitespace (including newlines and tabs) into a single
3
+ * space and trims the result.
4
+ * @example normalizeWhitespace(" hello\n\tworld ") // "hello world"
5
+ */
6
+ export function normalizeWhitespace(str: string): string {
7
+ return str.replace(/\s+/g, " ").trim();
8
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Picks the singular or plural form based on a count.
3
+ * If `plural` is omitted, appends `"s"` to the singular form.
4
+ * @example pluralize(1, "apple") // "apple"
5
+ * @example pluralize(2, "apple") // "apples"
6
+ * @example pluralize(2, "child", "children") // "children"
7
+ */
8
+ export function pluralize(
9
+ count: number,
10
+ singular: string,
11
+ plural?: string,
12
+ ): string {
13
+ if (count === 1) return singular;
14
+ return plural ?? `${singular}s`;
15
+ }
@@ -0,0 +1,12 @@
1
+ import { stripDiacritics } from "./stripDiacritics.js";
2
+
3
+ /**
4
+ * Converts a string to a URL-friendly slug.
5
+ * @example slugify("Hello, World!") // "hello-world"
6
+ */
7
+ export function slugify(str: string): string {
8
+ return stripDiacritics(str)
9
+ .toLowerCase()
10
+ .replace(/[^a-z0-9]+/g, "-")
11
+ .replace(/^-+|-+$/g, "");
12
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Splits a string into lowercase-friendly word tokens. Handles camelCase,
3
+ * PascalCase, ACRONYMTransitions, snake_case, kebab-case, and whitespace.
4
+ */
5
+ export function splitWords(str: string): string[] {
6
+ if (!str) return [];
7
+ return str
8
+ .replace(/([a-z\d])([A-Z])/g, "$1 $2")
9
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
10
+ .split(/[\s_\-]+/)
11
+ .filter(Boolean);
12
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Removes diacritical marks from a string.
3
+ * @example stripDiacritics("café") // "cafe"
4
+ */
5
+ export function stripDiacritics(str: string): string {
6
+ return str.normalize("NFD").replace(/\p{Diacritic}/gu, "");
7
+ }
@@ -0,0 +1,17 @@
1
+ import { splitWords } from "./splitWords.js";
2
+
3
+ /**
4
+ * Converts a string to `camelCase`.
5
+ * @example toCamelCase("hello_world") // "helloWorld"
6
+ */
7
+ export function toCamelCase(str: string): string {
8
+ const words = splitWords(str);
9
+ if (words.length === 0) return "";
10
+ return words
11
+ .map((word, index) => {
12
+ const lower = word.toLowerCase();
13
+ if (index === 0) return lower;
14
+ return lower.charAt(0).toUpperCase() + lower.slice(1);
15
+ })
16
+ .join("");
17
+ }
@@ -0,0 +1,11 @@
1
+ import { splitWords } from "./splitWords.js";
2
+
3
+ /**
4
+ * Converts a string to `kebab-case`.
5
+ * @example toKebabCase("helloWorld") // "hello-world"
6
+ */
7
+ export function toKebabCase(str: string): string {
8
+ return splitWords(str)
9
+ .map((word) => word.toLowerCase())
10
+ .join("-");
11
+ }
@@ -0,0 +1,14 @@
1
+ import { splitWords } from "./splitWords.js";
2
+
3
+ /**
4
+ * Converts a string to `PascalCase`.
5
+ * @example toPascalCase("hello_world") // "HelloWorld"
6
+ */
7
+ export function toPascalCase(str: string): string {
8
+ return splitWords(str)
9
+ .map((word) => {
10
+ const lower = word.toLowerCase();
11
+ return lower.charAt(0).toUpperCase() + lower.slice(1);
12
+ })
13
+ .join("");
14
+ }
@@ -0,0 +1,11 @@
1
+ import { splitWords } from "./splitWords.js";
2
+
3
+ /**
4
+ * Converts a string to `snake_case`.
5
+ * @example toSnakeCase("helloWorld") // "hello_world"
6
+ */
7
+ export function toSnakeCase(str: string): string {
8
+ return splitWords(str)
9
+ .map((word) => word.toLowerCase())
10
+ .join("_");
11
+ }
@@ -0,0 +1,45 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { toStartCase } from "./toStartCase";
4
+
5
+ describe("toStartCase", () => {
6
+ it("converts underscore_case to Start Case", () => {
7
+ expect(toStartCase("hello_world")).toBe("Hello World");
8
+ expect(toStartCase("multiple_word_string")).toBe("Multiple Word String");
9
+ expect(toStartCase("with_numbers_123")).toBe("With Numbers 123");
10
+ });
11
+
12
+ it("converts camelCase to Start Case", () => {
13
+ expect(toStartCase("helloWorld")).toBe("Hello World");
14
+ expect(toStartCase("multipleWordString")).toBe("Multiple Word String");
15
+ expect(toStartCase("withNumbers123")).toBe("With Numbers123");
16
+ });
17
+
18
+ it("handles already capitalized words", () => {
19
+ expect(toStartCase("Hello World")).toBe("Hello World");
20
+ expect(toStartCase("HELLO WORLD")).toBe("HELLO WORLD");
21
+ });
22
+
23
+ it("capitalizes first letter of each word", () => {
24
+ expect(toStartCase("hello world")).toBe("Hello World");
25
+ expect(toStartCase("a small sentence")).toBe("A Small Sentence");
26
+ });
27
+
28
+ it("handles empty string", () => {
29
+ expect(toStartCase("")).toBe("");
30
+ });
31
+
32
+ it("handles single word", () => {
33
+ expect(toStartCase("hello")).toBe("Hello");
34
+ expect(toStartCase("a")).toBe("A");
35
+ });
36
+
37
+ it("handles mixed formats", () => {
38
+ expect(toStartCase("hello_camelCased-string")).toBe(
39
+ "Hello Camel Cased-string",
40
+ );
41
+ expect(toStartCase("mixed_case-with SPACES")).toBe(
42
+ "Mixed Case-with SPACES",
43
+ );
44
+ });
45
+ });
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Converts a string to Start Case format
3
+ * Similar to the functionality in the 'to-start-case' package
4
+ *
5
+ * @param str The input string to convert
6
+ * @returns The converted string in Start Case format
7
+ * @example
8
+ * toStartCase('hello_world') // 'Hello World'
9
+ * toStartCase('helloWorld') // 'Hello World'
10
+ * toStartCase('hello-world') // 'Hello-world'
11
+ *
12
+ * FYI hyphens will be kept so this will not convert kebab-case to Start Case
13
+ */
14
+ export function toStartCase(str: string): string {
15
+ if (!str) return "";
16
+
17
+ return str
18
+ .replace(/_/g, " ")
19
+ .replace(/([a-z])([A-Z])/g, (_str, $1, $2) => $1 + " " + $2)
20
+ .replace(/(\s|^)(\w)/g, (_str, $1, $2) => $1 + $2.toUpperCase());
21
+ }
@@ -0,0 +1,29 @@
1
+ export interface TruncateOptions {
2
+ /** The ellipsis suffix appended when truncation occurs. Default `"…"`. */
3
+ ellipsis?: string;
4
+ /** If `true`, truncates on the last word boundary inside the limit. */
5
+ wordBoundary?: boolean;
6
+ }
7
+
8
+ /**
9
+ * Truncates a string to a maximum length, appending an ellipsis when shortened.
10
+ * The returned string (including ellipsis) will not exceed `maxLength`.
11
+ * @example truncate("Hello world", 8) // "Hello w…"
12
+ */
13
+ export function truncate(
14
+ str: string,
15
+ maxLength: number,
16
+ options: TruncateOptions = {},
17
+ ): string {
18
+ const { ellipsis = "…", wordBoundary = false } = options;
19
+ if (!str || str.length <= maxLength) return str;
20
+ if (maxLength <= ellipsis.length) return ellipsis.slice(0, maxLength);
21
+
22
+ const sliceLength = maxLength - ellipsis.length;
23
+ let truncated = str.slice(0, sliceLength);
24
+ if (wordBoundary) {
25
+ const lastSpace = truncated.lastIndexOf(" ");
26
+ if (lastSpace > 0) truncated = truncated.slice(0, lastSpace);
27
+ }
28
+ return truncated + ellipsis;
29
+ }
@@ -1 +1,2 @@
1
1
  // Utility functions — add exports here
2
+ export * from './formatters/index.js';