@fuzdev/fuz_util 0.42.0 → 0.44.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 (59) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +19 -12
  3. package/dist/async.d.ts +2 -2
  4. package/dist/async.d.ts.map +1 -1
  5. package/dist/async.js +2 -2
  6. package/dist/benchmark.d.ts +179 -0
  7. package/dist/benchmark.d.ts.map +1 -0
  8. package/dist/benchmark.js +400 -0
  9. package/dist/benchmark_baseline.d.ts +195 -0
  10. package/dist/benchmark_baseline.d.ts.map +1 -0
  11. package/dist/benchmark_baseline.js +388 -0
  12. package/dist/benchmark_format.d.ts +87 -0
  13. package/dist/benchmark_format.d.ts.map +1 -0
  14. package/dist/benchmark_format.js +266 -0
  15. package/dist/benchmark_stats.d.ts +112 -0
  16. package/dist/benchmark_stats.d.ts.map +1 -0
  17. package/dist/benchmark_stats.js +219 -0
  18. package/dist/benchmark_types.d.ts +174 -0
  19. package/dist/benchmark_types.d.ts.map +1 -0
  20. package/dist/benchmark_types.js +1 -0
  21. package/dist/git.d.ts +12 -0
  22. package/dist/git.d.ts.map +1 -1
  23. package/dist/git.js +14 -0
  24. package/dist/library_json.d.ts +3 -3
  25. package/dist/library_json.d.ts.map +1 -1
  26. package/dist/library_json.js +1 -1
  27. package/dist/maths.d.ts +4 -0
  28. package/dist/maths.d.ts.map +1 -1
  29. package/dist/maths.js +8 -0
  30. package/dist/object.js +1 -1
  31. package/dist/source_json.d.ts +4 -4
  32. package/dist/stats.d.ts +180 -0
  33. package/dist/stats.d.ts.map +1 -0
  34. package/dist/stats.js +402 -0
  35. package/dist/string.d.ts +13 -0
  36. package/dist/string.d.ts.map +1 -1
  37. package/dist/string.js +58 -0
  38. package/dist/time.d.ts +165 -0
  39. package/dist/time.d.ts.map +1 -0
  40. package/dist/time.js +264 -0
  41. package/dist/timings.d.ts +1 -7
  42. package/dist/timings.d.ts.map +1 -1
  43. package/dist/timings.js +16 -16
  44. package/package.json +21 -19
  45. package/src/lib/async.ts +3 -3
  46. package/src/lib/benchmark.ts +498 -0
  47. package/src/lib/benchmark_baseline.ts +538 -0
  48. package/src/lib/benchmark_format.ts +314 -0
  49. package/src/lib/benchmark_stats.ts +311 -0
  50. package/src/lib/benchmark_types.ts +197 -0
  51. package/src/lib/git.ts +24 -0
  52. package/src/lib/library_json.ts +3 -3
  53. package/src/lib/maths.ts +8 -0
  54. package/src/lib/object.ts +1 -1
  55. package/src/lib/stats.ts +534 -0
  56. package/src/lib/string.ts +66 -0
  57. package/src/lib/time.ts +319 -0
  58. package/src/lib/timings.ts +17 -17
  59. package/src/lib/types.ts +2 -2
package/dist/stats.js ADDED
@@ -0,0 +1,402 @@
1
+ /**
2
+ * Statistical analysis utilities.
3
+ * Pure functions with zero dependencies - can be used standalone for any data analysis.
4
+ */
5
+ // Statistical constants (defaults)
6
+ const DEFAULT_IQR_MULTIPLIER = 1.5;
7
+ const DEFAULT_MAD_Z_SCORE_THRESHOLD = 3.5;
8
+ const DEFAULT_MAD_Z_SCORE_EXTREME = 5.0;
9
+ const DEFAULT_MAD_CONSTANT = 0.6745; // For normal distribution approximation
10
+ const DEFAULT_OUTLIER_RATIO_HIGH = 0.3;
11
+ const DEFAULT_OUTLIER_RATIO_EXTREME = 0.4;
12
+ const DEFAULT_OUTLIER_KEEP_RATIO = 0.8;
13
+ const DEFAULT_CONFIDENCE_Z = 1.96; // 95% confidence
14
+ const DEFAULT_MIN_SAMPLE_SIZE = 3;
15
+ /**
16
+ * Calculate the mean (average) of an array of numbers.
17
+ */
18
+ export const stats_mean = (values) => {
19
+ if (values.length === 0)
20
+ return NaN;
21
+ return values.reduce((sum, val) => sum + val, 0) / values.length;
22
+ };
23
+ /**
24
+ * Calculate the median of an array of numbers.
25
+ */
26
+ export const stats_median = (values) => {
27
+ if (values.length === 0)
28
+ return NaN;
29
+ const sorted = [...values].sort((a, b) => a - b);
30
+ const mid = Math.floor(sorted.length / 2);
31
+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
32
+ };
33
+ /**
34
+ * Calculate the standard deviation of an array of numbers.
35
+ * Uses population standard deviation (divides by n, not n-1).
36
+ * For benchmarks with many samples, this is typically appropriate.
37
+ */
38
+ export const stats_std_dev = (values, mean) => {
39
+ if (values.length === 0)
40
+ return NaN;
41
+ const m = mean ?? stats_mean(values);
42
+ const variance = values.reduce((sum, val) => sum + (val - m) ** 2, 0) / values.length;
43
+ return Math.sqrt(variance);
44
+ };
45
+ /**
46
+ * Calculate the variance of an array of numbers.
47
+ */
48
+ export const stats_variance = (values, mean) => {
49
+ if (values.length === 0)
50
+ return NaN;
51
+ const m = mean ?? stats_mean(values);
52
+ return values.reduce((sum, val) => sum + (val - m) ** 2, 0) / values.length;
53
+ };
54
+ /**
55
+ * Calculate a percentile of an array of numbers using linear interpolation.
56
+ * Uses the "R-7" method (default in R, NumPy, Excel) which interpolates between
57
+ * data points for more accurate percentile estimates, especially with smaller samples.
58
+ * @param values - Array of numbers
59
+ * @param p - Percentile (0-1, e.g., 0.95 for 95th percentile)
60
+ */
61
+ export const stats_percentile = (values, p) => {
62
+ if (values.length === 0)
63
+ return NaN;
64
+ if (values.length === 1)
65
+ return values[0];
66
+ const sorted = [...values].sort((a, b) => a - b);
67
+ const n = sorted.length;
68
+ // R-7 method: index = (n - 1) * p
69
+ const index = (n - 1) * p;
70
+ const lower = Math.floor(index);
71
+ const upper = Math.ceil(index);
72
+ if (lower === upper) {
73
+ return sorted[lower];
74
+ }
75
+ // Linear interpolation between the two nearest values
76
+ const fraction = index - lower;
77
+ return sorted[lower] + fraction * (sorted[upper] - sorted[lower]);
78
+ };
79
+ /**
80
+ * Calculate the coefficient of variation (CV).
81
+ * CV = standard deviation / mean, expressed as a ratio.
82
+ * Useful for comparing relative variability between datasets.
83
+ */
84
+ export const stats_cv = (mean, std_dev) => {
85
+ if (mean === 0)
86
+ return NaN;
87
+ return std_dev / mean;
88
+ };
89
+ /**
90
+ * Calculate min and max values.
91
+ */
92
+ export const stats_min_max = (values) => {
93
+ if (values.length === 0)
94
+ return { min: NaN, max: NaN };
95
+ let min = values[0];
96
+ let max = values[0];
97
+ for (let i = 1; i < values.length; i++) {
98
+ const val = values[i];
99
+ if (val < min)
100
+ min = val;
101
+ if (val > max)
102
+ max = val;
103
+ }
104
+ return { min, max };
105
+ };
106
+ /**
107
+ * Detect outliers using the IQR (Interquartile Range) method.
108
+ * Values outside [Q1 - multiplier*IQR, Q3 + multiplier*IQR] are considered outliers.
109
+ */
110
+ export const stats_outliers_iqr = (values, options) => {
111
+ const iqr_multiplier = options?.iqr_multiplier ?? DEFAULT_IQR_MULTIPLIER;
112
+ const min_sample_size = options?.min_sample_size ?? DEFAULT_MIN_SAMPLE_SIZE;
113
+ if (values.length < min_sample_size) {
114
+ return { cleaned: values, outliers: [] };
115
+ }
116
+ const sorted = [...values].sort((a, b) => a - b);
117
+ const q1 = sorted[Math.floor(sorted.length * 0.25)];
118
+ const q3 = sorted[Math.floor(sorted.length * 0.75)];
119
+ const iqr = q3 - q1;
120
+ if (iqr === 0) {
121
+ return { cleaned: values, outliers: [] };
122
+ }
123
+ const lower_bound = q1 - iqr_multiplier * iqr;
124
+ const upper_bound = q3 + iqr_multiplier * iqr;
125
+ const cleaned = [];
126
+ const outliers = [];
127
+ for (const value of values) {
128
+ if (value < lower_bound || value > upper_bound) {
129
+ outliers.push(value);
130
+ }
131
+ else {
132
+ cleaned.push(value);
133
+ }
134
+ }
135
+ return { cleaned, outliers };
136
+ };
137
+ /**
138
+ * Detect outliers using the MAD (Median Absolute Deviation) method.
139
+ * More robust than IQR for skewed distributions.
140
+ * Uses modified Z-score: |0.6745 * (x - median) / MAD|
141
+ * Values with modified Z-score > threshold are considered outliers.
142
+ */
143
+ export const stats_outliers_mad = (values, options) => {
144
+ const z_score_threshold = options?.z_score_threshold ?? DEFAULT_MAD_Z_SCORE_THRESHOLD;
145
+ const z_score_extreme = options?.z_score_extreme ?? DEFAULT_MAD_Z_SCORE_EXTREME;
146
+ const mad_constant = options?.mad_constant ?? DEFAULT_MAD_CONSTANT;
147
+ const outlier_ratio_high = options?.outlier_ratio_high ?? DEFAULT_OUTLIER_RATIO_HIGH;
148
+ const outlier_ratio_extreme = options?.outlier_ratio_extreme ?? DEFAULT_OUTLIER_RATIO_EXTREME;
149
+ const outlier_keep_ratio = options?.outlier_keep_ratio ?? DEFAULT_OUTLIER_KEEP_RATIO;
150
+ const min_sample_size = options?.min_sample_size ?? DEFAULT_MIN_SAMPLE_SIZE;
151
+ const iqr_options = options?.iqr_options;
152
+ if (values.length < min_sample_size) {
153
+ return { cleaned: values, outliers: [] };
154
+ }
155
+ const sorted = [...values].sort((a, b) => a - b);
156
+ const median = stats_median(sorted);
157
+ // Calculate MAD (Median Absolute Deviation)
158
+ const deviations = values.map((v) => Math.abs(v - median));
159
+ const sorted_deviations = [...deviations].sort((a, b) => a - b);
160
+ const mad = stats_median(sorted_deviations);
161
+ // If MAD is zero, fall back to IQR method
162
+ if (mad === 0) {
163
+ return stats_outliers_iqr(values, iqr_options);
164
+ }
165
+ // Use modified Z-score with MAD
166
+ let cleaned = [];
167
+ let outliers = [];
168
+ for (const value of values) {
169
+ const modified_z_score = (mad_constant * (value - median)) / mad;
170
+ if (Math.abs(modified_z_score) > z_score_threshold) {
171
+ outliers.push(value);
172
+ }
173
+ else {
174
+ cleaned.push(value);
175
+ }
176
+ }
177
+ // If too many outliers, increase threshold and try again
178
+ if (outliers.length > values.length * outlier_ratio_high) {
179
+ cleaned = [];
180
+ outliers = [];
181
+ for (const value of values) {
182
+ const modified_z_score = (mad_constant * (value - median)) / mad;
183
+ if (Math.abs(modified_z_score) > z_score_extreme) {
184
+ outliers.push(value);
185
+ }
186
+ else {
187
+ cleaned.push(value);
188
+ }
189
+ }
190
+ // If still too many outliers, keep closest values to median
191
+ if (outliers.length > values.length * outlier_ratio_extreme) {
192
+ const with_distances = values.map((v) => ({
193
+ value: v,
194
+ distance: Math.abs(v - median),
195
+ }));
196
+ with_distances.sort((a, b) => a.distance - b.distance);
197
+ const keep_count = Math.floor(values.length * outlier_keep_ratio);
198
+ cleaned = with_distances.slice(0, keep_count).map((d) => d.value);
199
+ outliers = with_distances.slice(keep_count).map((d) => d.value);
200
+ }
201
+ }
202
+ return { cleaned, outliers };
203
+ };
204
+ /**
205
+ * Common z-scores for confidence intervals.
206
+ */
207
+ export const STATS_CONFIDENCE_Z_SCORES = {
208
+ 0.8: 1.282,
209
+ 0.9: 1.645,
210
+ 0.95: 1.96,
211
+ 0.99: 2.576,
212
+ 0.999: 3.291,
213
+ };
214
+ /**
215
+ * Convert a confidence level (0-1) to a z-score.
216
+ * Uses a lookup table for common values, approximates others.
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * stats_confidence_level_to_z_score(0.95); // 1.96
221
+ * stats_confidence_level_to_z_score(0.99); // 2.576
222
+ * ```
223
+ */
224
+ export const stats_confidence_level_to_z_score = (level) => {
225
+ if (level <= 0 || level >= 1) {
226
+ throw new Error('Confidence level must be between 0 and 1 (exclusive)');
227
+ }
228
+ // Check lookup table first
229
+ if (level in STATS_CONFIDENCE_Z_SCORES) {
230
+ return STATS_CONFIDENCE_Z_SCORES[level];
231
+ }
232
+ // For confidence level c, we want z such that P(-z < Z < z) = c
233
+ // This means Φ(z) = (1 + c) / 2, so z = Φ⁻¹((1 + c) / 2)
234
+ // Using Φ⁻¹(p) = √2 * erfinv(2p - 1)
235
+ const p = (1 + level) / 2; // e.g., 0.95 -> 0.975
236
+ const x = 2 * p - 1; // Argument for erfinv, e.g., 0.975 -> 0.95
237
+ // Winitzki approximation for erfinv
238
+ const a = 0.147;
239
+ const ln_term = Math.log(1 - x * x);
240
+ const term1 = 2 / (Math.PI * a) + ln_term / 2;
241
+ const erfinv = Math.sign(x) * Math.sqrt(Math.sqrt(term1 * term1 - ln_term / a) - term1);
242
+ return Math.SQRT2 * erfinv;
243
+ };
244
+ /**
245
+ * Calculate confidence interval for the mean.
246
+ * @param values - Array of numbers
247
+ * @param options - Configuration options
248
+ * @returns [lower_bound, upper_bound]
249
+ */
250
+ export const stats_confidence_interval = (values, options) => {
251
+ if (values.length === 0)
252
+ return [NaN, NaN];
253
+ const mean = stats_mean(values);
254
+ const std_dev = stats_std_dev(values, mean);
255
+ return stats_confidence_interval_from_summary(mean, std_dev, values.length, options);
256
+ };
257
+ /**
258
+ * Calculate confidence interval from summary statistics (mean, std_dev, sample_size).
259
+ * Useful when raw data is not available.
260
+ * @param mean - Mean of the data
261
+ * @param std_dev - Standard deviation of the data
262
+ * @param sample_size - Number of samples
263
+ * @param options - Configuration options
264
+ * @returns [lower_bound, upper_bound]
265
+ */
266
+ export const stats_confidence_interval_from_summary = (mean, std_dev, sample_size, options) => {
267
+ // z_score takes precedence, then confidence_level, then default
268
+ const z_score = options?.z_score ??
269
+ (options?.confidence_level
270
+ ? stats_confidence_level_to_z_score(options.confidence_level)
271
+ : null) ??
272
+ DEFAULT_CONFIDENCE_Z;
273
+ if (sample_size === 0)
274
+ return [NaN, NaN];
275
+ const se = std_dev / Math.sqrt(sample_size);
276
+ const margin = z_score * se;
277
+ return [mean - margin, mean + margin];
278
+ };
279
+ /**
280
+ * Calculate Welch's t-test statistic and degrees of freedom.
281
+ * Welch's t-test is more robust than Student's t-test when variances are unequal.
282
+ *
283
+ * @param mean1 - Mean of first sample
284
+ * @param std1 - Standard deviation of first sample
285
+ * @param n1 - Size of first sample
286
+ * @param mean2 - Mean of second sample
287
+ * @param std2 - Standard deviation of second sample
288
+ * @param n2 - Size of second sample
289
+ */
290
+ export const stats_welch_t_test = (mean1, std1, n1, mean2, std2, n2) => {
291
+ const var1 = std1 ** 2;
292
+ const var2 = std2 ** 2;
293
+ const se1 = var1 / n1;
294
+ const se2 = var2 / n2;
295
+ const t_statistic = (mean1 - mean2) / Math.sqrt(se1 + se2);
296
+ // Welch-Satterthwaite degrees of freedom
297
+ const numerator = (se1 + se2) ** 2;
298
+ const denominator = se1 ** 2 / (n1 - 1) + se2 ** 2 / (n2 - 1);
299
+ const degrees_of_freedom = numerator / denominator;
300
+ return { t_statistic, degrees_of_freedom };
301
+ };
302
+ /**
303
+ * Standard normal CDF approximation (Abramowitz and Stegun formula 7.1.26).
304
+ */
305
+ export const stats_normal_cdf = (x) => {
306
+ const t = 1 / (1 + 0.2316419 * Math.abs(x));
307
+ const d = 0.3989423 * Math.exp((-x * x) / 2);
308
+ const p = d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274))));
309
+ return x > 0 ? 1 - p : p;
310
+ };
311
+ /**
312
+ * Log gamma function approximation (Lanczos approximation).
313
+ */
314
+ export const stats_ln_gamma = (z) => {
315
+ const g = 7;
316
+ const c = [
317
+ 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,
318
+ -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,
319
+ 1.5056327351493116e-7,
320
+ ];
321
+ if (z < 0.5) {
322
+ return Math.log(Math.PI / Math.sin(Math.PI * z)) - stats_ln_gamma(1 - z);
323
+ }
324
+ const z_adj = z - 1;
325
+ let x = c[0];
326
+ for (let i = 1; i < g + 2; i++) {
327
+ x += c[i] / (z_adj + i);
328
+ }
329
+ const t = z_adj + g + 0.5;
330
+ return 0.5 * Math.log(2 * Math.PI) + (z_adj + 0.5) * Math.log(t) - t + Math.log(x);
331
+ };
332
+ /**
333
+ * Approximate regularized incomplete beta function for p-value calculation.
334
+ * Uses continued fraction expansion for reasonable accuracy.
335
+ */
336
+ export const stats_incomplete_beta = (x, a, b) => {
337
+ // Simple approximation using the relationship between beta and normal distributions
338
+ // For our use case (t-distribution p-values), this provides sufficient accuracy
339
+ if (x <= 0)
340
+ return 0;
341
+ if (x >= 1)
342
+ return 1;
343
+ // Use symmetry if needed
344
+ if (x > (a + 1) / (a + b + 2)) {
345
+ return 1 - stats_incomplete_beta(1 - x, b, a);
346
+ }
347
+ // Continued fraction approximation (first few terms)
348
+ const lnBeta = stats_ln_gamma(a) + stats_ln_gamma(b) - stats_ln_gamma(a + b);
349
+ const front = Math.exp(Math.log(x) * a + Math.log(1 - x) * b - lnBeta) / a;
350
+ // Simple continued fraction (limited iterations for speed)
351
+ let f = 1;
352
+ let c = 1;
353
+ let d = 0;
354
+ for (let m = 1; m <= 100; m++) {
355
+ const m2 = 2 * m;
356
+ // Even step
357
+ let aa = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2));
358
+ d = 1 + aa * d;
359
+ if (Math.abs(d) < 1e-30)
360
+ d = 1e-30;
361
+ c = 1 + aa / c;
362
+ if (Math.abs(c) < 1e-30)
363
+ c = 1e-30;
364
+ d = 1 / d;
365
+ f *= d * c;
366
+ // Odd step
367
+ aa = (-(a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1));
368
+ d = 1 + aa * d;
369
+ if (Math.abs(d) < 1e-30)
370
+ d = 1e-30;
371
+ c = 1 + aa / c;
372
+ if (Math.abs(c) < 1e-30)
373
+ c = 1e-30;
374
+ d = 1 / d;
375
+ const delta = d * c;
376
+ f *= delta;
377
+ if (Math.abs(delta - 1) < 1e-8)
378
+ break;
379
+ }
380
+ return front * f;
381
+ };
382
+ /**
383
+ * Approximate two-tailed p-value from t-distribution.
384
+ * For large df (>100), uses normal approximation.
385
+ * For smaller df, uses incomplete beta function.
386
+ *
387
+ * @param t - Absolute value of t-statistic
388
+ * @param df - Degrees of freedom
389
+ * @returns Two-tailed p-value
390
+ */
391
+ export const stats_t_distribution_p_value = (t, df) => {
392
+ // Use normal approximation for large df
393
+ if (df > 100) {
394
+ return 2 * (1 - stats_normal_cdf(t));
395
+ }
396
+ // For smaller df, use a more accurate approximation
397
+ // Based on the incomplete beta function relationship
398
+ const x = df / (df + t * t);
399
+ const a = df / 2;
400
+ const b = 0.5;
401
+ return stats_incomplete_beta(x, a, b);
402
+ };
package/dist/string.d.ts CHANGED
@@ -48,4 +48,17 @@ export declare const strip_ansi: (str: string) => string;
48
48
  * @source https://2ality.com/2025/04/stringification-javascript.html
49
49
  */
50
50
  export declare const stringify: (value: unknown) => string;
51
+ /**
52
+ * Calculate the display width of a string in terminal columns.
53
+ * - Strips ANSI escape codes (they have 0 width)
54
+ * - Emojis and other wide characters take 2 columns
55
+ * - Tab characters take 4 columns
56
+ * - Newlines and other control characters take 0 columns
57
+ * - Uses `Intl.Segmenter` to properly handle grapheme clusters (e.g., family emoji "👨‍👩‍👧‍👦")
58
+ */
59
+ export declare const string_display_width: (str: string) => number;
60
+ /**
61
+ * Pad a string to a target display width (accounting for wide characters).
62
+ */
63
+ export declare const pad_width: (str: string, target_width: number, align?: "left" | "right") => string;
51
64
  //# sourceMappingURL=string.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"string.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/string.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK,MAAM,EAAE,WAAW,MAAM,EAAE,eAAc,KAAG,MAMzE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,GAAI,QAAQ,MAAM,EAAE,UAAU,MAAM,KAAG,MAG9D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,SAAS,GAAI,QAAQ,MAAM,EAAE,UAAU,MAAM,KAAG,MAG5D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,GAAI,QAAQ,MAAM,EAAE,UAAU,MAAM,KAAG,MAK9D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,MAAM,EAAE,UAAU,MAAM,KAAG,MAK/D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,MAAM,EAAE,SAAS,MAAM,KAAG,MAG9D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,UAAU,GAAI,QAAQ,MAAM,EAAE,SAAS,MAAM,KAAG,MAG5D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK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SAAS,GAAG,IAAI,EAAE,eAAY,KAAG,MAC9C,CAAC;AAE3B;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,KAAK,MAAM,KAAG,MACI,CAAC;AAEnD;;GAEG;AACH,eAAO,MAAM,UAAU,GAAI,KAAK,MAAM,KAAG,MAAsD,CAAC;AAEhG;;;;GAIG;AACH,eAAO,MAAM,SAAS,GAAI,OAAO,OAAO,KAAG,MACwC,CAAC;AAEpF;;;;;;;GAOG;AACH,eAAO,MAAM,oBAAoB,GAAI,KAAK,MAAM,KAAG,MAuClD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,SAAS,GACrB,KAAK,MAAM,EACX,cAAc,MAAM,EACpB,QAAO,MAAM,GAAG,OAAgB,KAC9B,MAQF,CAAC"}
package/dist/string.js CHANGED
@@ -90,3 +90,61 @@ export const strip_ansi = (str) => str.replaceAll(/\x1B\[[0-9;]*[a-zA-Z]/g, '');
90
90
  * @source https://2ality.com/2025/04/stringification-javascript.html
91
91
  */
92
92
  export const stringify = (value) => typeof value === 'bigint' ? value + 'n' : (JSON.stringify(value) ?? String(value)); // eslint-disable-line @typescript-eslint/no-unnecessary-condition
93
+ /**
94
+ * Calculate the display width of a string in terminal columns.
95
+ * - Strips ANSI escape codes (they have 0 width)
96
+ * - Emojis and other wide characters take 2 columns
97
+ * - Tab characters take 4 columns
98
+ * - Newlines and other control characters take 0 columns
99
+ * - Uses `Intl.Segmenter` to properly handle grapheme clusters (e.g., family emoji "👨‍👩‍👧‍👦")
100
+ */
101
+ export const string_display_width = (str) => {
102
+ // Strip ANSI codes first (they have 0 display width)
103
+ const clean = strip_ansi(str);
104
+ let width = 0;
105
+ const segmenter = new Intl.Segmenter();
106
+ for (const { segment } of segmenter.segment(clean)) {
107
+ const code = segment.codePointAt(0);
108
+ // Handle control characters
109
+ if (code === 0x09) {
110
+ // Tab = 4 columns
111
+ width += 4;
112
+ continue;
113
+ }
114
+ if (code < 0x20 || (code >= 0x7f && code < 0xa0)) {
115
+ // Other control characters (including newline) = 0 width
116
+ continue;
117
+ }
118
+ // Emoji and other wide characters (rough heuristic)
119
+ // - Most emoji are in range 0x1F300-0x1FAFF
120
+ // - Some are in 0x2600-0x27BF (misc symbols)
121
+ // - CJK characters 0x4E00-0x9FFF also double-width
122
+ // - Grapheme clusters with multiple code points (like ZWJ sequences) are typically emoji
123
+ if (segment.length > 1 || // Multi-codepoint graphemes (ZWJ sequences, etc.)
124
+ (code >= 0x1f300 && code <= 0x1faff) ||
125
+ (code >= 0x2600 && code <= 0x27bf) ||
126
+ (code >= 0x1f600 && code <= 0x1f64f) ||
127
+ (code >= 0x1f680 && code <= 0x1f6ff) ||
128
+ (code >= 0x4e00 && code <= 0x9fff) // CJK
129
+ ) {
130
+ width += 2;
131
+ }
132
+ else {
133
+ width += 1;
134
+ }
135
+ }
136
+ return width;
137
+ };
138
+ /**
139
+ * Pad a string to a target display width (accounting for wide characters).
140
+ */
141
+ export const pad_width = (str, target_width, align = 'left') => {
142
+ const current_width = string_display_width(str);
143
+ const padding = Math.max(0, target_width - current_width);
144
+ if (align === 'left') {
145
+ return str + ' '.repeat(padding);
146
+ }
147
+ else {
148
+ return ' '.repeat(padding) + str;
149
+ }
150
+ };
package/dist/time.d.ts ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Time utilities.
3
+ * Provides cross-platform high-resolution timing and measurement helpers.
4
+ */
5
+ /**
6
+ * Timer interface for measuring elapsed time.
7
+ * Returns time in nanoseconds for maximum precision.
8
+ */
9
+ export interface Timer {
10
+ /** Get current time in nanoseconds */
11
+ now: () => number;
12
+ }
13
+ /**
14
+ * Node.js high-resolution timer using process.hrtime.bigint().
15
+ * Provides true nanosecond precision.
16
+ */
17
+ export declare const timer_node: Timer;
18
+ /**
19
+ * Browser high-resolution timer using performance.now().
20
+ * Converts milliseconds to nanoseconds for consistent API.
21
+ *
22
+ * **Precision varies by browser due to Spectre/Meltdown mitigations:**
23
+ * - Chrome: ~100μs (coarsened)
24
+ * - Firefox: ~1ms (rounded)
25
+ * - Safari: ~100μs
26
+ * - Node.js: ~1μs
27
+ *
28
+ * For nanosecond-precision benchmarks, use Node.js with `timer_node`.
29
+ */
30
+ export declare const timer_browser: Timer;
31
+ /**
32
+ * Auto-detected timer based on environment.
33
+ * Uses process.hrtime in Node.js, performance.now() in browsers.
34
+ * The timer function is detected once and cached for performance.
35
+ */
36
+ export declare const timer_default: Timer;
37
+ /**
38
+ * Time units and conversions.
39
+ */
40
+ export declare const TIME_NS_PER_US = 1000;
41
+ export declare const TIME_NS_PER_MS = 1000000;
42
+ export declare const TIME_NS_PER_SEC = 1000000000;
43
+ /**
44
+ * Convert nanoseconds to microseconds.
45
+ */
46
+ export declare const time_ns_to_us: (ns: number) => number;
47
+ /**
48
+ * Convert nanoseconds to milliseconds.
49
+ */
50
+ export declare const time_ns_to_ms: (ns: number) => number;
51
+ /**
52
+ * Convert nanoseconds to seconds.
53
+ */
54
+ export declare const time_ns_to_sec: (ns: number) => number;
55
+ /**
56
+ * Time unit for formatting.
57
+ */
58
+ export type TimeUnit = 'ns' | 'us' | 'ms' | 's';
59
+ /**
60
+ * Display labels for time units (uses proper Unicode μ for microseconds).
61
+ */
62
+ export declare const TIME_UNIT_DISPLAY: Record<TimeUnit, string>;
63
+ /**
64
+ * Detect the best time unit for a set of nanosecond values.
65
+ * Chooses the unit where most values fall in the range 1-9999.
66
+ * @param values_ns - Array of times in nanoseconds
67
+ * @returns Best unit to use for all values
68
+ */
69
+ export declare const time_unit_detect_best: (values_ns: Array<number>) => TimeUnit;
70
+ /**
71
+ * Format time with a specific unit.
72
+ * @param ns - Time in nanoseconds
73
+ * @param unit - Unit to use ('ns', 'us', 'ms', 's')
74
+ * @param decimals - Number of decimal places (default: 2)
75
+ * @returns Formatted string like "3.87μs"
76
+ */
77
+ export declare const time_format: (ns: number, unit: TimeUnit, decimals?: number) => string;
78
+ /**
79
+ * Format time with adaptive units (ns/μs/ms/s) based on magnitude.
80
+ * @param ns - Time in nanoseconds
81
+ * @param decimals - Number of decimal places (default: 2)
82
+ * @returns Formatted string like "3.87μs" or "1.23ms"
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * time_format_adaptive(1500) // "1.50μs"
87
+ * time_format_adaptive(3870) // "3.87μs"
88
+ * time_format_adaptive(1500000) // "1.50ms"
89
+ * time_format_adaptive(1500000000) // "1.50s"
90
+ * ```
91
+ */
92
+ export declare const time_format_adaptive: (ns: number, decimals?: number) => string;
93
+ /**
94
+ * Result from timing a function execution.
95
+ * All times in nanoseconds for maximum precision.
96
+ */
97
+ export interface TimeResult {
98
+ /** Elapsed time in nanoseconds */
99
+ elapsed_ns: number;
100
+ /** Elapsed time in microseconds (convenience) */
101
+ elapsed_us: number;
102
+ /** Elapsed time in milliseconds (convenience) */
103
+ elapsed_ms: number;
104
+ /** Start time in nanoseconds (from timer.now()) */
105
+ started_at_ns: number;
106
+ /** End time in nanoseconds (from timer.now()) */
107
+ ended_at_ns: number;
108
+ }
109
+ /**
110
+ * Time an asynchronous function execution.
111
+ * @param fn - Async function to time
112
+ * @param timer - Timer to use (defaults to timer_default)
113
+ * @returns Object containing the function result and timing information
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const {result, timing} = await time_async(async () => {
118
+ * await fetch('https://api.example.com/data');
119
+ * return 42;
120
+ * });
121
+ * console.log(`Result: ${result}, took ${time_format_adaptive(timing.elapsed_ns)}`);
122
+ * ```
123
+ */
124
+ export declare const time_async: <T>(fn: () => Promise<T>, timer?: Timer) => Promise<{
125
+ result: T;
126
+ timing: TimeResult;
127
+ }>;
128
+ /**
129
+ * Time a synchronous function execution.
130
+ * @param fn - Sync function to time
131
+ * @param timer - Timer to use (defaults to timer_default)
132
+ * @returns Object containing the function result and timing information
133
+ *
134
+ * @example
135
+ * ```ts
136
+ * const {result, timing} = time_sync(() => {
137
+ * return expensive_computation();
138
+ * });
139
+ * console.log(`Result: ${result}, took ${time_format_adaptive(timing.elapsed_ns)}`);
140
+ * ```
141
+ */
142
+ export declare const time_sync: <T>(fn: () => T, timer?: Timer) => {
143
+ result: T;
144
+ timing: TimeResult;
145
+ };
146
+ /**
147
+ * Measure multiple executions of a function and return all timings.
148
+ * @param fn - Function to measure (sync or async)
149
+ * @param iterations - Number of times to execute
150
+ * @param timer - Timer to use (defaults to timer_default)
151
+ * @returns Array of elapsed times in nanoseconds
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * const timings_ns = await time_measure(async () => {
156
+ * await process_data();
157
+ * }, 100);
158
+ *
159
+ * import {BenchmarkStats} from './benchmark_stats.js';
160
+ * const stats = new BenchmarkStats(timings_ns);
161
+ * console.log(`Mean: ${time_format_adaptive(stats.mean_ns)}`);
162
+ * ```
163
+ */
164
+ export declare const time_measure: (fn: () => unknown, iterations: number, timer?: Timer) => Promise<Array<number>>;
165
+ //# sourceMappingURL=time.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/time.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;GAGG;AACH,MAAM,WAAW,KAAK;IACrB,sCAAsC;IACtC,GAAG,EAAE,MAAM,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,eAAO,MAAM,UAAU,EAAE,KAKxB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,aAAa,EAAE,KAI3B,CAAC;AAmCF;;;;GAIG;AACH,eAAO,MAAM,aAAa,EAAE,KAE3B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,cAAc,OAAQ,CAAC;AACpC,eAAO,MAAM,cAAc,UAAY,CAAC;AACxC,eAAO,MAAM,eAAe,aAAgB,CAAC;AAE7C;;GAEG;AACH,eAAO,MAAM,aAAa,GAAI,IAAI,MAAM,KAAG,MAA6B,CAAC;AAEzE;;GAEG;AACH,eAAO,MAAM,aAAa,GAAI,IAAI,MAAM,KAAG,MAA6B,CAAC;AAEzE;;GAEG;AACH,eAAO,MAAM,cAAc,GAAI,IAAI,MAAM,KA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