@seedcord/utils 0.3.8 → 0.4.0-next.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/README.md +1 -1
- package/dist/index.cjs +490 -273
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -265
- package/dist/index.d.mts +759 -0
- package/dist/index.mjs +461 -254
- package/dist/index.mjs.map +1 -1
- package/package.json +24 -20
- package/dist/index.d.ts +0 -265
package/dist/index.mjs
CHANGED
|
@@ -1,307 +1,514 @@
|
|
|
1
|
-
import { readdir } from
|
|
2
|
-
import * as path from
|
|
3
|
-
import { SeedcordTypeError, SeedcordErrorCode, SeedcordError } from '@seedcord/services';
|
|
1
|
+
import { readdir } from "node:fs/promises";
|
|
2
|
+
import * as path from "node:path";
|
|
4
3
|
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
//#region src/misc/assertNever.ts
|
|
5
|
+
/**
|
|
6
|
+
* Exhaustiveness guard for discriminated unions. Place in the `default` branch of a `switch` over a
|
|
7
|
+
* union's discriminant: if a new variant is added without a matching case, the call fails to compile.
|
|
8
|
+
* Throws at runtime if reached with a value the types said was impossible.
|
|
9
|
+
*/
|
|
10
|
+
function assertNever(value) {
|
|
11
|
+
throw new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/misc/directory.ts
|
|
16
|
+
/**
|
|
17
|
+
* Determines if a directory entry is a TypeScript or JavaScript file.
|
|
18
|
+
*
|
|
19
|
+
* @param entry - The directory entry to check.
|
|
20
|
+
* @returns True if the entry is a file ending with .ts or .js.
|
|
21
|
+
*/
|
|
7
22
|
function isTsOrJsFile(entry) {
|
|
8
|
-
|
|
23
|
+
return entry.isFile() && (entry.name.endsWith(".ts") || entry.name.endsWith(".js")) && !entry.name.endsWith(".d.ts") && !entry.name.endsWith(".map");
|
|
9
24
|
}
|
|
10
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Recursively traverses through a directory, importing all .ts and .js files and applying a callback to each import.
|
|
27
|
+
*
|
|
28
|
+
* @param dir - The directory path to traverse.
|
|
29
|
+
* @param callback - A function that will be called for each imported module. It receives the full file path, the file's relative path, and the imported module as arguments.
|
|
30
|
+
* @returns A Promise that resolves when the traversal is complete.
|
|
31
|
+
*/
|
|
11
32
|
async function traverseDirectory(dir, callback, logger) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
33
|
+
let entries;
|
|
34
|
+
try {
|
|
35
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
36
|
+
} catch (err) {
|
|
37
|
+
logger.error(`Failed to read directory ${dir}`, err);
|
|
38
|
+
entries = [];
|
|
39
|
+
}
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
const fullPath = path.join(dir, entry.name);
|
|
42
|
+
const relativePath = path.relative(process.cwd(), fullPath);
|
|
43
|
+
if (entry.isDirectory()) await traverseDirectory(fullPath, callback, logger);
|
|
44
|
+
else if (isTsOrJsFile(entry)) await callback(fullPath, relativePath, await import(fullPath));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Formats a file path relative to the current working directory.
|
|
49
|
+
* @param filePath - The file path to format.
|
|
50
|
+
* @param options - Formatting options.
|
|
51
|
+
* @returns The formatted file path.
|
|
52
|
+
*/
|
|
53
|
+
function formatFilePath(filePath, options = {}) {
|
|
54
|
+
const { onlyDir = false, prefix = "./" } = options;
|
|
55
|
+
return `${prefix}${onlyDir ? path.relative(process.cwd(), filePath.replace(/\/[^/]*$/, "")) : path.relative(process.cwd(), filePath)}`;
|
|
31
56
|
}
|
|
32
|
-
__name(traverseDirectory, "traverseDirectory");
|
|
33
57
|
|
|
34
|
-
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/misc/fyShuffle.ts
|
|
60
|
+
/**
|
|
61
|
+
* Shuffles an array using the Fisher-Yates algorithm.
|
|
62
|
+
* This function creates a new array with the same elements in a random order,
|
|
63
|
+
* without modifying the original array.
|
|
64
|
+
*
|
|
65
|
+
* @typeParam TArray - The type of elements in the array
|
|
66
|
+
* @param items - The array to shuffle
|
|
67
|
+
* @returns A new array with the same elements in a random order
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```typescript
|
|
71
|
+
* const numbers = [1, 2, 3, 4, 5];
|
|
72
|
+
* const shuffled = fyShuffle(numbers);
|
|
73
|
+
* // shuffled might be [3, 1, 5, 2, 4]
|
|
74
|
+
* // numbers is still [1, 2, 3, 4, 5]
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
35
77
|
function fyShuffle(items) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
];
|
|
43
|
-
}
|
|
44
|
-
return array;
|
|
78
|
+
const array = items.slice();
|
|
79
|
+
for (let i = array.length - 1; i > 0; i--) {
|
|
80
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
81
|
+
[array[i], array[j]] = [array[j], array[i]];
|
|
82
|
+
}
|
|
83
|
+
return array;
|
|
45
84
|
}
|
|
46
|
-
__name(fyShuffle, "fyShuffle");
|
|
47
85
|
|
|
48
|
-
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region src/numbers/currentTime.ts
|
|
88
|
+
/**
|
|
89
|
+
* Return current time in seconds
|
|
90
|
+
*/
|
|
49
91
|
function currentTime() {
|
|
50
|
-
|
|
92
|
+
return Math.floor(Date.now() / 1e3);
|
|
51
93
|
}
|
|
52
|
-
__name(currentTime, "currentTime");
|
|
53
94
|
|
|
54
|
-
|
|
95
|
+
//#endregion
|
|
96
|
+
//#region src/numbers/generateCode.ts
|
|
97
|
+
/**
|
|
98
|
+
* Generates a random numeric code with the specified number of digits.
|
|
99
|
+
*
|
|
100
|
+
* @param digits - The number of digits for the generated code.
|
|
101
|
+
* @returns A random numeric code with the specified number of digits.
|
|
102
|
+
*/
|
|
55
103
|
function generateCode(digits) {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
60
|
-
__name(generateCode, "generateCode");
|
|
61
|
-
function hexToNumber(hex) {
|
|
62
|
-
if (typeof hex !== "string") {
|
|
63
|
-
throw new SeedcordTypeError(SeedcordErrorCode.UtilHexInputType);
|
|
64
|
-
}
|
|
65
|
-
const normalized = hex.replace(/^#/, "");
|
|
66
|
-
if (!/^[0-9a-fA-F]+$/.test(normalized)) {
|
|
67
|
-
throw new SeedcordError(SeedcordErrorCode.UtilHexInvalid);
|
|
68
|
-
}
|
|
69
|
-
const converted = parseInt(normalized, 16);
|
|
70
|
-
if (Number.isNaN(converted)) {
|
|
71
|
-
throw new SeedcordError(SeedcordErrorCode.UtilHexInvalid);
|
|
72
|
-
}
|
|
73
|
-
return converted;
|
|
104
|
+
const min = Math.pow(10, digits - 1);
|
|
105
|
+
const max = Math.pow(10, digits) - 1;
|
|
106
|
+
return Math.floor(Math.random() * (max - min + 1) + min);
|
|
74
107
|
}
|
|
75
|
-
__name(hexToNumber, "hexToNumber");
|
|
76
108
|
|
|
77
|
-
|
|
109
|
+
//#endregion
|
|
110
|
+
//#region src/numbers/ordinal.ts
|
|
111
|
+
/**
|
|
112
|
+
* Returns the ordinal suffix for a given number.
|
|
113
|
+
*
|
|
114
|
+
* @param n - The number to get the ordinal for
|
|
115
|
+
* @returns The number with its ordinal suffix
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ordinal(1); // "1st"
|
|
119
|
+
* ordinal(22); // "22nd"
|
|
120
|
+
* ordinal(13); // "13th"
|
|
121
|
+
*/
|
|
78
122
|
function ordinal(n) {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
return `${n}${suffix}`;
|
|
123
|
+
const s = [
|
|
124
|
+
"th",
|
|
125
|
+
"st",
|
|
126
|
+
"nd",
|
|
127
|
+
"rd"
|
|
128
|
+
];
|
|
129
|
+
const v = n % 100;
|
|
130
|
+
const suffix = s[(v - 20) % 10] ?? s[v] ?? s[0];
|
|
131
|
+
if (!suffix) return `${n}th`;
|
|
132
|
+
return `${n}${suffix}`;
|
|
90
133
|
}
|
|
91
|
-
__name(ordinal, "ordinal");
|
|
92
134
|
|
|
93
|
-
|
|
135
|
+
//#endregion
|
|
136
|
+
//#region src/numbers/percentage.ts
|
|
137
|
+
/**
|
|
138
|
+
* Takes two numbers and returns the percentage of the first number in the second number with two decimal places.
|
|
139
|
+
*
|
|
140
|
+
* @param num1 - The first number.
|
|
141
|
+
* @param num2 - The second number.
|
|
142
|
+
*
|
|
143
|
+
* @returns The percentage of the first number in the second number with two decimal places.
|
|
144
|
+
*/
|
|
94
145
|
function percentage(num1, num2) {
|
|
95
|
-
|
|
146
|
+
return Number((num1 / num2 * 100).toFixed(2));
|
|
96
147
|
}
|
|
97
|
-
__name(percentage, "percentage");
|
|
98
148
|
|
|
99
|
-
|
|
149
|
+
//#endregion
|
|
150
|
+
//#region src/numbers/round.ts
|
|
151
|
+
/**
|
|
152
|
+
* Rounds a number to a specified number of decimal places.
|
|
153
|
+
*
|
|
154
|
+
* @param num - The number to be rounded.
|
|
155
|
+
* @param precision - The number of decimal places to round to.
|
|
156
|
+
* @returns The rounded number.
|
|
157
|
+
*/
|
|
100
158
|
function round(num, precision) {
|
|
101
|
-
|
|
102
|
-
|
|
159
|
+
const factor = Math.pow(10, precision);
|
|
160
|
+
return Math.round((num + Number.EPSILON) * factor) / factor;
|
|
103
161
|
}
|
|
104
|
-
__name(round, "round");
|
|
105
162
|
|
|
106
|
-
|
|
163
|
+
//#endregion
|
|
164
|
+
//#region src/numbers/roundToDenomination.ts
|
|
165
|
+
/**
|
|
166
|
+
* Rounds a number to a string representation with a denomination suffix.
|
|
167
|
+
* @param num - The number to round.
|
|
168
|
+
* @example
|
|
169
|
+
* ```ts
|
|
170
|
+
* roundToDenomination(1234); // "1.2K"
|
|
171
|
+
* roundToDenomination(10000, ['k', 'm', 'b', 't', 'q']); // "10k"
|
|
172
|
+
* roundToDenomination(12345678); // "12.3M"
|
|
173
|
+
* ```
|
|
174
|
+
* @returns The rounded number as a string with a denomination suffix.
|
|
175
|
+
*/
|
|
107
176
|
function roundToDenomination(num, opts) {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
result = Math.ceil(Number(result)).toString();
|
|
133
|
-
}
|
|
134
|
-
if (result.endsWith(".0")) {
|
|
135
|
-
result = result.substring(0, result.length - 2);
|
|
136
|
-
}
|
|
137
|
-
if (result === "1000") {
|
|
138
|
-
index += 1;
|
|
139
|
-
result = "1";
|
|
140
|
-
}
|
|
141
|
-
return result + (index >= 0 ? suffixes[index] : "");
|
|
177
|
+
const { suffixes = [
|
|
178
|
+
"K",
|
|
179
|
+
"M",
|
|
180
|
+
"B",
|
|
181
|
+
"T",
|
|
182
|
+
"Q"
|
|
183
|
+
], precision = 1 } = opts ?? {};
|
|
184
|
+
if (num < 1e4) return num.toString();
|
|
185
|
+
let index = -1;
|
|
186
|
+
let temp = num;
|
|
187
|
+
while (temp >= 1e3 && index < suffixes.length - 1) {
|
|
188
|
+
temp /= 1e3;
|
|
189
|
+
index++;
|
|
190
|
+
}
|
|
191
|
+
let result;
|
|
192
|
+
if (temp % 1 === 0) result = temp.toString();
|
|
193
|
+
else result = (Math.round(temp * Math.pow(10, precision + 1)) / Math.pow(10, precision + 1)).toFixed(precision);
|
|
194
|
+
if (result.endsWith(".9")) result = Math.ceil(Number(result)).toString();
|
|
195
|
+
if (result.endsWith(".0")) result = result.substring(0, result.length - 2);
|
|
196
|
+
if (result === "1000") {
|
|
197
|
+
index += 1;
|
|
198
|
+
result = "1";
|
|
199
|
+
}
|
|
200
|
+
return result + (index >= 0 ? suffixes[index] : "");
|
|
142
201
|
}
|
|
143
|
-
__name(roundToDenomination, "roundToDenomination");
|
|
144
202
|
|
|
145
|
-
|
|
203
|
+
//#endregion
|
|
204
|
+
//#region src/objects/filterCirculars.ts
|
|
205
|
+
/**
|
|
206
|
+
* Creates a clean, JSON safe copy of a value and replaces circular references with a marker.
|
|
207
|
+
*
|
|
208
|
+
* In `json` mode it behaves like stringify then parse with a replacer that handles cycles and BigInt.
|
|
209
|
+
* In `decycle` mode it first clones without using toJSON, then you can stringify the result later.
|
|
210
|
+
*
|
|
211
|
+
* @typeParam ObjType - Type of the input value.
|
|
212
|
+
* @typeParam Marker - Marker string used for circular references.
|
|
213
|
+
*
|
|
214
|
+
* @param value - The value to clone safely.
|
|
215
|
+
* @param options - Optional configuration.
|
|
216
|
+
*
|
|
217
|
+
* @returns A JSON safe structure with circular references replaced by the marker.
|
|
218
|
+
*
|
|
219
|
+
* @example
|
|
220
|
+
* ```ts
|
|
221
|
+
* interface Test {
|
|
222
|
+
* name: string;
|
|
223
|
+
* self?: Test;
|
|
224
|
+
* }
|
|
225
|
+
*
|
|
226
|
+
* const obj: Test = { name: 'seedcord' };
|
|
227
|
+
* obj.self = obj;
|
|
228
|
+
*
|
|
229
|
+
* const clean = filterCirculars(obj);
|
|
230
|
+
* // ^? { name: string; self?: "[Circular]" | { ... } }
|
|
231
|
+
* console.log(clean.self); // "[Circular]"
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
146
234
|
function filterCirculars(value, options) {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
}
|
|
235
|
+
const logger = options?.logger;
|
|
236
|
+
const marker = options?.marker ?? "[Circular]";
|
|
237
|
+
if ((options?.mode ?? "decycle") === "json") return json(value, marker, logger);
|
|
238
|
+
try {
|
|
239
|
+
return decycle(value, marker);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
logger?.error("filterCirculars decycle error", error);
|
|
242
|
+
return { "[unserializable]": "decycle failed" };
|
|
243
|
+
}
|
|
157
244
|
}
|
|
158
|
-
|
|
245
|
+
/**
|
|
246
|
+
* Attempts to build a JSONified object using JSON.stringify and JSON.parse.
|
|
247
|
+
*
|
|
248
|
+
* @internal
|
|
249
|
+
*/
|
|
159
250
|
function json(value, marker, logger) {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
logger?.error("filterCirculars parse error", error);
|
|
186
|
-
logger?.error("bad JSON", json2);
|
|
187
|
-
return value;
|
|
188
|
-
}
|
|
251
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
252
|
+
let json;
|
|
253
|
+
try {
|
|
254
|
+
json = JSON.stringify(value, (_k, v) => {
|
|
255
|
+
if (typeof v === "bigint") return v.toString();
|
|
256
|
+
if (typeof v === "object" && v !== null) {
|
|
257
|
+
const obj = v;
|
|
258
|
+
if (seen.has(obj)) return marker;
|
|
259
|
+
seen.add(obj);
|
|
260
|
+
}
|
|
261
|
+
return v;
|
|
262
|
+
});
|
|
263
|
+
} catch (error) {
|
|
264
|
+
logger?.error("filterCirculars stringify error", error);
|
|
265
|
+
if (typeof value === "object" && value !== null) logger?.error("top level keys", Object.keys(value));
|
|
266
|
+
return { "[unserializable]": "stringify failed" };
|
|
267
|
+
}
|
|
268
|
+
if (typeof json !== "string") return { "[unserializable]": "stringify returned undefined" };
|
|
269
|
+
try {
|
|
270
|
+
return JSON.parse(json);
|
|
271
|
+
} catch (error) {
|
|
272
|
+
logger?.error("filterCirculars parse error", error);
|
|
273
|
+
logger?.error("bad JSON", json);
|
|
274
|
+
return { "[unserializable]": "parse failed" };
|
|
275
|
+
}
|
|
189
276
|
}
|
|
190
|
-
|
|
277
|
+
/**
|
|
278
|
+
* Builds a JSON safe clone without calling toJSON on class instances.
|
|
279
|
+
*
|
|
280
|
+
* @internal
|
|
281
|
+
*/
|
|
191
282
|
function decycle(input, marker, seen = /* @__PURE__ */ new WeakSet()) {
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
}
|
|
214
|
-
const out = {};
|
|
215
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
216
|
-
if (typeof v === "function") continue;
|
|
217
|
-
out[k] = recur(v);
|
|
218
|
-
}
|
|
219
|
-
return out;
|
|
220
|
-
}, "recur");
|
|
221
|
-
return recur(input);
|
|
283
|
+
const recur = (val) => {
|
|
284
|
+
if (val === null) return null;
|
|
285
|
+
const t = typeof val;
|
|
286
|
+
if (t === "bigint") return val.toString();
|
|
287
|
+
if (t !== "object") return val;
|
|
288
|
+
const obj = val;
|
|
289
|
+
if (seen.has(obj)) return marker;
|
|
290
|
+
seen.add(obj);
|
|
291
|
+
if (obj instanceof Date) return obj.toISOString();
|
|
292
|
+
if (obj instanceof RegExp) return obj.toString();
|
|
293
|
+
if (Array.isArray(obj)) return obj.map((item) => recur(item));
|
|
294
|
+
if (obj instanceof Map) return Array.from(obj, ([k, v]) => [recur(k), recur(v)]);
|
|
295
|
+
if (obj instanceof Set) return Array.from(obj, (v) => recur(v));
|
|
296
|
+
const out = {};
|
|
297
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
298
|
+
if (typeof v === "function") continue;
|
|
299
|
+
out[k] = recur(v);
|
|
300
|
+
}
|
|
301
|
+
return out;
|
|
302
|
+
};
|
|
303
|
+
return recur(input);
|
|
222
304
|
}
|
|
223
|
-
__name(decycle, "decycle");
|
|
224
305
|
|
|
225
|
-
|
|
306
|
+
//#endregion
|
|
307
|
+
//#region src/objects/hasKeys.ts
|
|
308
|
+
/**
|
|
309
|
+
* Checks for the presence of nested keys in an object that's possibly a distributed union, narrowing the object type accordingly.
|
|
310
|
+
*
|
|
311
|
+
* Checks if an object has the specified nested keys and that their values are not null or undefined. If they are not, the object type is narrowed to reflect the presence of these keys with their respective types from the original distributed union object.
|
|
312
|
+
*
|
|
313
|
+
* @param obj - The object to check.
|
|
314
|
+
* @param keys - An array of dot-notation paths to check.
|
|
315
|
+
* @returns True if all keys exist and are non-null/defined, narrowing the object type.
|
|
316
|
+
*
|
|
317
|
+
* @example
|
|
318
|
+
* ```ts
|
|
319
|
+
* interface Test {
|
|
320
|
+
* a?: {
|
|
321
|
+
* b?: {
|
|
322
|
+
* c?: string;
|
|
323
|
+
* };
|
|
324
|
+
* } | null;
|
|
325
|
+
* x?: number | null;
|
|
326
|
+
* }
|
|
327
|
+
*
|
|
328
|
+
* const obj: Test = { a: { b: { c: 'hello' } }, x: 42 };
|
|
329
|
+
*
|
|
330
|
+
* if (hasKeys(obj, ['a.b.c', 'x'])) {
|
|
331
|
+
* // Here, obj is narrowed to:
|
|
332
|
+
* // {
|
|
333
|
+
* // a: { b: { c: string } };
|
|
334
|
+
* // x: number;
|
|
335
|
+
* // }
|
|
336
|
+
* console.log(obj.a.b.c.toUpperCase()); // Safe to access and use
|
|
337
|
+
* console.log(obj.x.toFixed(2)); // Safe to access and use
|
|
338
|
+
* }
|
|
339
|
+
* ```
|
|
340
|
+
*/
|
|
341
|
+
function hasKeys(obj, keys) {
|
|
342
|
+
return keys.every((key) => {
|
|
343
|
+
const parts = key.split(".");
|
|
344
|
+
let current = obj;
|
|
345
|
+
for (const part of parts) {
|
|
346
|
+
if (current === null || current === void 0 || typeof current !== "object" && typeof current !== "function") return false;
|
|
347
|
+
if (!(part in current)) return false;
|
|
348
|
+
current = current[part];
|
|
349
|
+
}
|
|
350
|
+
return current !== null && current !== void 0;
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
//#endregion
|
|
355
|
+
//#region src/objects/keepDefined.ts
|
|
356
|
+
/**
|
|
357
|
+
* Copies only the keys whose values are defined.
|
|
358
|
+
*
|
|
359
|
+
* @typeParam TObject - the original object type you're pulling from
|
|
360
|
+
* @typeParam TKey - the keys to copy when defined
|
|
361
|
+
* @param source - the object to read values from
|
|
362
|
+
* @param keys - optional list of keys to include when present. If omitted, all keys are considered
|
|
363
|
+
*
|
|
364
|
+
* @example
|
|
365
|
+
* ```ts
|
|
366
|
+
* interface Config {
|
|
367
|
+
* host?: string;
|
|
368
|
+
* port?: number;
|
|
369
|
+
* user?: string;
|
|
370
|
+
* password?: string;
|
|
371
|
+
* }
|
|
372
|
+
*
|
|
373
|
+
* const config: Config = {
|
|
374
|
+
* host: 'localhost',
|
|
375
|
+
* port: undefined,
|
|
376
|
+
* user: 'admin',
|
|
377
|
+
* password: undefined
|
|
378
|
+
* };
|
|
379
|
+
*
|
|
380
|
+
* const definedConfig = keepDefined(config, 'host', 'port', 'user', 'password');
|
|
381
|
+
* // Result: { host: 'localhost', user: 'admin' }
|
|
382
|
+
* ```
|
|
383
|
+
*/
|
|
226
384
|
function keepDefined(source, ...keys) {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
}
|
|
235
|
-
return result;
|
|
385
|
+
const selectedKeys = keys.length > 0 ? keys : Object.keys(source);
|
|
386
|
+
const result = {};
|
|
387
|
+
for (const key of selectedKeys) {
|
|
388
|
+
const value = source[key];
|
|
389
|
+
if (value !== void 0 && value !== null) result[key] = value;
|
|
390
|
+
}
|
|
391
|
+
return result;
|
|
236
392
|
}
|
|
237
|
-
__name(keepDefined, "keepDefined");
|
|
238
393
|
|
|
239
|
-
|
|
394
|
+
//#endregion
|
|
395
|
+
//#region src/strings/capitalize.ts
|
|
396
|
+
/**
|
|
397
|
+
* Returns the word with its first letter capitalized and the rest in lowercase.
|
|
398
|
+
* @param word - The word to be formatted.
|
|
399
|
+
* @returns The formatted word.
|
|
400
|
+
*/
|
|
240
401
|
function capitalize(word) {
|
|
241
|
-
|
|
402
|
+
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
|
|
242
403
|
}
|
|
243
|
-
__name(capitalize, "capitalize");
|
|
244
404
|
|
|
245
|
-
|
|
405
|
+
//#endregion
|
|
406
|
+
//#region src/strings/longestStringLength.ts
|
|
407
|
+
/**
|
|
408
|
+
* Function takes an array of strings or numbers and returns the number of characters in the longest string/number
|
|
409
|
+
*
|
|
410
|
+
* @param arr - The array of strings or numbers
|
|
411
|
+
* @returns The length of the longest element when converted to string
|
|
412
|
+
*/
|
|
246
413
|
function longestStringLength(arr) {
|
|
247
|
-
|
|
414
|
+
return Math.max(...arr.map((el) => el.toString().length));
|
|
248
415
|
}
|
|
249
|
-
__name(longestStringLength, "longestStringLength");
|
|
250
416
|
|
|
251
|
-
|
|
417
|
+
//#endregion
|
|
418
|
+
//#region src/strings/generateAsciiTable.ts
|
|
419
|
+
/**
|
|
420
|
+
* Generates an ASCII table from the provided data.
|
|
421
|
+
*
|
|
422
|
+
* @param data - The data to be displayed in the table.
|
|
423
|
+
* @returns The generated ASCII table as a string.
|
|
424
|
+
*/
|
|
252
425
|
function generateAsciiTable(data) {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
426
|
+
if (data.length === 0) return "";
|
|
427
|
+
const firstRow = data[0];
|
|
428
|
+
if (!firstRow || firstRow.length === 0) return "";
|
|
429
|
+
let table = "";
|
|
430
|
+
const columnWidths = [];
|
|
431
|
+
for (let i = 0; i < firstRow.length; i++) {
|
|
432
|
+
let maxWidth = 0;
|
|
433
|
+
for (const row of data) {
|
|
434
|
+
const cell = row[i];
|
|
435
|
+
if (cell !== void 0) maxWidth = Math.max(maxWidth, cell.length);
|
|
436
|
+
}
|
|
437
|
+
columnWidths.push(maxWidth);
|
|
438
|
+
}
|
|
439
|
+
const createLine = (char, left, intersect, right) => {
|
|
440
|
+
let line = left;
|
|
441
|
+
columnWidths.forEach((width, index) => {
|
|
442
|
+
line += char.repeat(width + 2);
|
|
443
|
+
if (index < columnWidths.length - 1) line += intersect;
|
|
444
|
+
else line += right;
|
|
445
|
+
});
|
|
446
|
+
line += "\n";
|
|
447
|
+
return line;
|
|
448
|
+
};
|
|
449
|
+
table += createLine("═", "╔", "╦", "╗");
|
|
450
|
+
data.forEach((row, rowIndex) => {
|
|
451
|
+
table += "║";
|
|
452
|
+
row.forEach((cell, columnIndex) => {
|
|
453
|
+
const columnWidth = columnWidths[columnIndex];
|
|
454
|
+
if (columnWidth !== void 0) table += ` ${cell.padEnd(columnWidth)} ║`;
|
|
455
|
+
});
|
|
456
|
+
table += "\n";
|
|
457
|
+
if (rowIndex < data.length - 1) table += createLine("─", "╠", "╬", "╣");
|
|
458
|
+
else table += createLine("═", "╚", "╩", "╝");
|
|
459
|
+
});
|
|
460
|
+
return table;
|
|
288
461
|
}
|
|
289
|
-
__name(generateAsciiTable, "generateAsciiTable");
|
|
290
462
|
|
|
291
|
-
|
|
463
|
+
//#endregion
|
|
464
|
+
//#region src/strings/prettify.ts
|
|
465
|
+
/**
|
|
466
|
+
* Converts a string from any common naming convention to human-readable format.
|
|
467
|
+
* Accepts camelCase, PascalCase, snake_case, and kebab-case input.
|
|
468
|
+
*
|
|
469
|
+
* @param key - The string to convert
|
|
470
|
+
* @param opts - Optional configuration
|
|
471
|
+
* @returns A space-separated, human-readable string
|
|
472
|
+
*
|
|
473
|
+
* @example
|
|
474
|
+
* prettify("camelCaseString") // "camel Case String"
|
|
475
|
+
* prettify("PascalCaseString") // "Pascal Case String"
|
|
476
|
+
* prettify("snake_case_string") // "snake case string"
|
|
477
|
+
* prettify("kebab-case-string") // "kebab case string"
|
|
478
|
+
* prettify("mixedCase_string-name") // "mixed Case string name"
|
|
479
|
+
*/
|
|
292
480
|
function prettify(key, opts) {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
481
|
+
const result = key.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]/g, " ").trim();
|
|
482
|
+
if (opts?.capitalize) return capitalize(result);
|
|
483
|
+
return result;
|
|
296
484
|
}
|
|
297
|
-
__name(prettify, "prettify");
|
|
298
485
|
|
|
299
|
-
|
|
486
|
+
//#endregion
|
|
487
|
+
//#region src/strings/prettyDifference.ts
|
|
488
|
+
/**
|
|
489
|
+
* Calculates the difference between two numbers and formats it as a string with a '+' prefix for positive differences.
|
|
490
|
+
*
|
|
491
|
+
* @param numBefore - The initial number value
|
|
492
|
+
* @param numAfter - The final number value
|
|
493
|
+
* @returns A string representing the difference, with a '+' sign for positive differences
|
|
494
|
+
*
|
|
495
|
+
* @example
|
|
496
|
+
* // Returns "+5"
|
|
497
|
+
* prettyDifference(10, 15);
|
|
498
|
+
*
|
|
499
|
+
* @example
|
|
500
|
+
* // Returns "-3"
|
|
501
|
+
* prettyDifference(10, 7);
|
|
502
|
+
*/
|
|
300
503
|
function prettyDifference(numBefore, numAfter) {
|
|
301
|
-
|
|
504
|
+
return (numAfter - numBefore > 0 ? `+${numAfter - numBefore}` : numAfter - numBefore).toString();
|
|
302
505
|
}
|
|
303
|
-
__name(prettyDifference, "prettyDifference");
|
|
304
506
|
|
|
305
|
-
|
|
306
|
-
//#
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region src/index.ts
|
|
509
|
+
/** Package version */
|
|
510
|
+
const version = "0.4.0-next.0";
|
|
511
|
+
|
|
512
|
+
//#endregion
|
|
513
|
+
export { assertNever, capitalize, currentTime, filterCirculars, formatFilePath, fyShuffle, generateAsciiTable, generateCode, hasKeys, isTsOrJsFile, keepDefined, longestStringLength, ordinal, percentage, prettify, prettyDifference, round, roundToDenomination, traverseDirectory, version };
|
|
307
514
|
//# sourceMappingURL=index.mjs.map
|