@holoscript/std 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/time.ts ADDED
@@ -0,0 +1,622 @@
1
+ /**
2
+ * @holoscript/std - Time Module
3
+ *
4
+ * Time, timer, and scheduling utilities for HoloScript Plus programs.
5
+ */
6
+
7
+ /**
8
+ * Get current timestamp in milliseconds
9
+ */
10
+ export function now(): number {
11
+ return Date.now();
12
+ }
13
+
14
+ /**
15
+ * Get high-resolution timestamp (for performance measurement)
16
+ */
17
+ export function hrTime(): number {
18
+ if (typeof performance !== 'undefined') {
19
+ return performance.now();
20
+ }
21
+ return Date.now();
22
+ }
23
+
24
+ /**
25
+ * Sleep for a specified number of milliseconds
26
+ */
27
+ export function sleep(ms: number): Promise<void> {
28
+ return new Promise((resolve) => setTimeout(resolve, ms));
29
+ }
30
+
31
+ /**
32
+ * Wait until a condition is true
33
+ */
34
+ export async function waitUntil(
35
+ condition: () => boolean | Promise<boolean>,
36
+ options: { timeout?: number; interval?: number } = {}
37
+ ): Promise<void> {
38
+ const { timeout = 30000, interval = 100 } = options;
39
+ const startTime = now();
40
+
41
+ while (true) {
42
+ if (await condition()) return;
43
+ if (now() - startTime > timeout) {
44
+ throw new Error('waitUntil timeout');
45
+ }
46
+ await sleep(interval);
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Execute a function with timeout
52
+ */
53
+ export async function withTimeout<T>(fn: () => Promise<T>, ms: number): Promise<T> {
54
+ return Promise.race([
55
+ fn(),
56
+ new Promise<T>((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms)),
57
+ ]);
58
+ }
59
+
60
+ /**
61
+ * Retry a function with exponential backoff
62
+ */
63
+ export async function retry<T>(
64
+ fn: () => Promise<T>,
65
+ options: {
66
+ maxAttempts?: number;
67
+ initialDelay?: number;
68
+ maxDelay?: number;
69
+ factor?: number;
70
+ onRetry?: (error: Error, attempt: number) => void;
71
+ } = {}
72
+ ): Promise<T> {
73
+ const { maxAttempts = 3, initialDelay = 1000, maxDelay = 30000, factor = 2, onRetry } = options;
74
+
75
+ let lastError: Error;
76
+ let delay = initialDelay;
77
+
78
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
79
+ try {
80
+ return await fn();
81
+ } catch (error) {
82
+ lastError = error instanceof Error ? error : new Error(String(error));
83
+
84
+ if (attempt === maxAttempts) break;
85
+
86
+ onRetry?.(lastError, attempt);
87
+ await sleep(delay);
88
+ delay = Math.min(delay * factor, maxDelay);
89
+ }
90
+ }
91
+
92
+ throw lastError!;
93
+ }
94
+
95
+ /**
96
+ * Debounce a function
97
+ */
98
+ export function debounce<T extends (...args: unknown[]) => unknown>(fn: T, ms: number): T {
99
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
100
+
101
+ return ((...args: unknown[]) => {
102
+ if (timeoutId) clearTimeout(timeoutId);
103
+ timeoutId = setTimeout(() => {
104
+ timeoutId = null;
105
+ fn(...args);
106
+ }, ms);
107
+ }) as T;
108
+ }
109
+
110
+ /**
111
+ * Throttle a function
112
+ */
113
+ export function throttle<T extends (...args: unknown[]) => unknown>(fn: T, ms: number): T {
114
+ let lastCall = 0;
115
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
116
+
117
+ return ((...args: unknown[]) => {
118
+ const elapsed = now() - lastCall;
119
+
120
+ if (elapsed >= ms) {
121
+ lastCall = now();
122
+ fn(...args);
123
+ } else if (!timeoutId) {
124
+ timeoutId = setTimeout(
125
+ () => {
126
+ lastCall = now();
127
+ timeoutId = null;
128
+ fn(...args);
129
+ },
130
+ ms - elapsed
131
+ );
132
+ }
133
+ }) as T;
134
+ }
135
+
136
+ /**
137
+ * Measure execution time of a function
138
+ */
139
+ export async function measure<T>(fn: () => T | Promise<T>): Promise<{ result: T; duration: number }> {
140
+ const start = hrTime();
141
+ const result = await fn();
142
+ const duration = hrTime() - start;
143
+ return { result, duration };
144
+ }
145
+
146
+ /**
147
+ * Measure execution time and log it
148
+ */
149
+ export async function timed<T>(label: string, fn: () => T | Promise<T>): Promise<T> {
150
+ const start = hrTime();
151
+ try {
152
+ return await fn();
153
+ } finally {
154
+ const duration = hrTime() - start;
155
+ console.log(`[${label}] ${duration.toFixed(2)}ms`);
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Simple stopwatch for measuring elapsed time
161
+ */
162
+ export class Stopwatch {
163
+ private startTime: number = 0;
164
+ private pausedTime: number = 0;
165
+ private running: boolean = false;
166
+
167
+ start(): this {
168
+ if (!this.running) {
169
+ this.startTime = hrTime() - this.pausedTime;
170
+ this.running = true;
171
+ }
172
+ return this;
173
+ }
174
+
175
+ stop(): number {
176
+ if (this.running) {
177
+ this.pausedTime = hrTime() - this.startTime;
178
+ this.running = false;
179
+ }
180
+ return this.pausedTime;
181
+ }
182
+
183
+ reset(): this {
184
+ this.startTime = 0;
185
+ this.pausedTime = 0;
186
+ this.running = false;
187
+ return this;
188
+ }
189
+
190
+ restart(): this {
191
+ return this.reset().start();
192
+ }
193
+
194
+ get elapsed(): number {
195
+ if (this.running) {
196
+ return hrTime() - this.startTime;
197
+ }
198
+ return this.pausedTime;
199
+ }
200
+
201
+ get isRunning(): boolean {
202
+ return this.running;
203
+ }
204
+
205
+ lap(): number {
206
+ const elapsed = this.elapsed;
207
+ this.restart();
208
+ return elapsed;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Interval timer with pause/resume support
214
+ */
215
+ export class IntervalTimer {
216
+ private intervalId: ReturnType<typeof setInterval> | null = null;
217
+ private callback: () => void;
218
+ private intervalMs: number;
219
+ private isPaused: boolean = false;
220
+
221
+ constructor(callback: () => void, intervalMs: number) {
222
+ this.callback = callback;
223
+ this.intervalMs = intervalMs;
224
+ }
225
+
226
+ start(): this {
227
+ if (!this.intervalId && !this.isPaused) {
228
+ this.intervalId = setInterval(this.callback, this.intervalMs);
229
+ }
230
+ return this;
231
+ }
232
+
233
+ stop(): this {
234
+ if (this.intervalId) {
235
+ clearInterval(this.intervalId);
236
+ this.intervalId = null;
237
+ }
238
+ this.isPaused = false;
239
+ return this;
240
+ }
241
+
242
+ pause(): this {
243
+ if (this.intervalId) {
244
+ clearInterval(this.intervalId);
245
+ this.intervalId = null;
246
+ this.isPaused = true;
247
+ }
248
+ return this;
249
+ }
250
+
251
+ resume(): this {
252
+ if (this.isPaused) {
253
+ this.isPaused = false;
254
+ this.intervalId = setInterval(this.callback, this.intervalMs);
255
+ }
256
+ return this;
257
+ }
258
+
259
+ get running(): boolean {
260
+ return this.intervalId !== null;
261
+ }
262
+
263
+ get paused(): boolean {
264
+ return this.isPaused;
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Countdown timer
270
+ */
271
+ export class CountdownTimer {
272
+ private remainingMs: number;
273
+ private startTime: number = 0;
274
+ private running: boolean = false;
275
+ private onTick?: (remaining: number) => void;
276
+ private onComplete?: () => void;
277
+ private tickIntervalId: ReturnType<typeof setInterval> | null = null;
278
+
279
+ constructor(
280
+ durationMs: number,
281
+ options: {
282
+ onTick?: (remaining: number) => void;
283
+ onComplete?: () => void;
284
+ tickInterval?: number;
285
+ } = {}
286
+ ) {
287
+ this.remainingMs = durationMs;
288
+ this.onTick = options.onTick;
289
+ this.onComplete = options.onComplete;
290
+
291
+ if (options.onTick && options.tickInterval) {
292
+ this.tickIntervalId = setInterval(() => {
293
+ if (this.running) {
294
+ this.onTick?.(this.remaining);
295
+ }
296
+ }, options.tickInterval);
297
+ }
298
+ }
299
+
300
+ start(): this {
301
+ if (!this.running && this.remainingMs > 0) {
302
+ this.startTime = hrTime();
303
+ this.running = true;
304
+ this.scheduleCompletion();
305
+ }
306
+ return this;
307
+ }
308
+
309
+ pause(): this {
310
+ if (this.running) {
311
+ this.remainingMs = Math.max(0, this.remainingMs - (hrTime() - this.startTime));
312
+ this.running = false;
313
+ }
314
+ return this;
315
+ }
316
+
317
+ resume(): this {
318
+ return this.start();
319
+ }
320
+
321
+ reset(durationMs?: number): this {
322
+ this.running = false;
323
+ this.remainingMs = durationMs ?? this.remainingMs;
324
+ return this;
325
+ }
326
+
327
+ stop(): this {
328
+ this.running = false;
329
+ if (this.tickIntervalId) {
330
+ clearInterval(this.tickIntervalId);
331
+ this.tickIntervalId = null;
332
+ }
333
+ return this;
334
+ }
335
+
336
+ get remaining(): number {
337
+ if (this.running) {
338
+ return Math.max(0, this.remainingMs - (hrTime() - this.startTime));
339
+ }
340
+ return this.remainingMs;
341
+ }
342
+
343
+ get isRunning(): boolean {
344
+ return this.running;
345
+ }
346
+
347
+ get isComplete(): boolean {
348
+ return this.remaining <= 0;
349
+ }
350
+
351
+ private scheduleCompletion(): void {
352
+ setTimeout(() => {
353
+ if (this.running && this.remaining <= 0) {
354
+ this.running = false;
355
+ this.onComplete?.();
356
+ }
357
+ }, this.remainingMs);
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Frame-based timer for game loops
363
+ */
364
+ export class FrameTimer {
365
+ private lastFrameTime: number = 0;
366
+ private deltaTime: number = 0;
367
+ private frameCount: number = 0;
368
+ private fps: number = 0;
369
+ private fpsUpdateInterval: number = 1000;
370
+ private lastFpsUpdate: number = 0;
371
+ private framesSinceLastFpsUpdate: number = 0;
372
+
373
+ /**
374
+ * Call at the start of each frame
375
+ */
376
+ update(): void {
377
+ const currentTime = hrTime();
378
+
379
+ if (this.lastFrameTime > 0) {
380
+ this.deltaTime = (currentTime - this.lastFrameTime) / 1000; // Convert to seconds
381
+ }
382
+
383
+ this.lastFrameTime = currentTime;
384
+ this.frameCount++;
385
+ this.framesSinceLastFpsUpdate++;
386
+
387
+ // Update FPS calculation
388
+ if (currentTime - this.lastFpsUpdate >= this.fpsUpdateInterval) {
389
+ this.fps = (this.framesSinceLastFpsUpdate * 1000) / (currentTime - this.lastFpsUpdate);
390
+ this.lastFpsUpdate = currentTime;
391
+ this.framesSinceLastFpsUpdate = 0;
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Get delta time in seconds since last frame
397
+ */
398
+ get delta(): number {
399
+ return this.deltaTime;
400
+ }
401
+
402
+ /**
403
+ * Get delta time in milliseconds since last frame
404
+ */
405
+ get deltaMs(): number {
406
+ return this.deltaTime * 1000;
407
+ }
408
+
409
+ /**
410
+ * Get total frame count
411
+ */
412
+ get frames(): number {
413
+ return this.frameCount;
414
+ }
415
+
416
+ /**
417
+ * Get current FPS (frames per second)
418
+ */
419
+ get currentFps(): number {
420
+ return this.fps;
421
+ }
422
+
423
+ /**
424
+ * Get total elapsed time in seconds
425
+ */
426
+ get totalTime(): number {
427
+ return this.lastFrameTime / 1000;
428
+ }
429
+
430
+ /**
431
+ * Reset the timer
432
+ */
433
+ reset(): void {
434
+ this.lastFrameTime = 0;
435
+ this.deltaTime = 0;
436
+ this.frameCount = 0;
437
+ this.fps = 0;
438
+ this.lastFpsUpdate = 0;
439
+ this.framesSinceLastFpsUpdate = 0;
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Schedule a callback to run after a delay
445
+ */
446
+ export function schedule(callback: () => void, delayMs: number): () => void {
447
+ const timeoutId = setTimeout(callback, delayMs);
448
+ return () => clearTimeout(timeoutId);
449
+ }
450
+
451
+ /**
452
+ * Schedule a callback to run at regular intervals
453
+ */
454
+ export function scheduleInterval(callback: () => void, intervalMs: number): () => void {
455
+ const intervalId = setInterval(callback, intervalMs);
456
+ return () => clearInterval(intervalId);
457
+ }
458
+
459
+ /**
460
+ * Schedule a callback to run on the next animation frame (browser only)
461
+ */
462
+ export function scheduleFrame(callback: (timestamp: number) => void): () => void {
463
+ if (typeof requestAnimationFrame !== 'undefined') {
464
+ const id = requestAnimationFrame(callback);
465
+ return () => cancelAnimationFrame(id);
466
+ }
467
+ // Fallback for non-browser environments
468
+ const id = setTimeout(() => callback(hrTime()), 16);
469
+ return () => clearTimeout(id);
470
+ }
471
+
472
+ /**
473
+ * Create a ticker that calls a callback at a target frame rate
474
+ */
475
+ export function createTicker(
476
+ callback: (delta: number) => void,
477
+ targetFps: number = 60
478
+ ): { start: () => void; stop: () => void } {
479
+ const frameTime = 1000 / targetFps;
480
+ let lastTime = 0;
481
+ let running = false;
482
+ let animationId: number | ReturnType<typeof setTimeout>;
483
+
484
+ const tick = (currentTime: number) => {
485
+ if (!running) return;
486
+
487
+ if (lastTime > 0) {
488
+ const delta = (currentTime - lastTime) / 1000;
489
+ callback(delta);
490
+ }
491
+ lastTime = currentTime;
492
+
493
+ if (typeof requestAnimationFrame !== 'undefined') {
494
+ animationId = requestAnimationFrame(tick);
495
+ } else {
496
+ animationId = setTimeout(() => tick(hrTime()), frameTime);
497
+ }
498
+ };
499
+
500
+ return {
501
+ start: () => {
502
+ if (!running) {
503
+ running = true;
504
+ lastTime = 0;
505
+ if (typeof requestAnimationFrame !== 'undefined') {
506
+ animationId = requestAnimationFrame(tick);
507
+ } else {
508
+ tick(hrTime());
509
+ }
510
+ }
511
+ },
512
+ stop: () => {
513
+ running = false;
514
+ if (typeof cancelAnimationFrame !== 'undefined') {
515
+ cancelAnimationFrame(animationId as number);
516
+ } else {
517
+ clearTimeout(animationId as ReturnType<typeof setTimeout>);
518
+ }
519
+ },
520
+ };
521
+ }
522
+
523
+ /**
524
+ * Date/time formatting utilities
525
+ */
526
+ export const DateTime = {
527
+ /**
528
+ * Format a date as ISO string
529
+ */
530
+ toISO(date: Date = new Date()): string {
531
+ return date.toISOString();
532
+ },
533
+
534
+ /**
535
+ * Format a date as local string
536
+ */
537
+ toLocal(date: Date = new Date()): string {
538
+ return date.toLocaleString();
539
+ },
540
+
541
+ /**
542
+ * Format a date using a pattern
543
+ * Supports: YYYY, MM, DD, HH, mm, ss, SSS
544
+ */
545
+ format(date: Date, pattern: string): string {
546
+ const pad = (n: number, width: number) => String(n).padStart(width, '0');
547
+
548
+ return pattern
549
+ .replace('YYYY', String(date.getFullYear()))
550
+ .replace('MM', pad(date.getMonth() + 1, 2))
551
+ .replace('DD', pad(date.getDate(), 2))
552
+ .replace('HH', pad(date.getHours(), 2))
553
+ .replace('mm', pad(date.getMinutes(), 2))
554
+ .replace('ss', pad(date.getSeconds(), 2))
555
+ .replace('SSS', pad(date.getMilliseconds(), 3));
556
+ },
557
+
558
+ /**
559
+ * Parse a date string
560
+ */
561
+ parse(dateString: string): Date {
562
+ return new Date(dateString);
563
+ },
564
+
565
+ /**
566
+ * Get difference between two dates in various units
567
+ */
568
+ diff(date1: Date, date2: Date, unit: 'ms' | 's' | 'm' | 'h' | 'd' = 'ms'): number {
569
+ const diffMs = date1.getTime() - date2.getTime();
570
+ switch (unit) {
571
+ case 'ms':
572
+ return diffMs;
573
+ case 's':
574
+ return diffMs / 1000;
575
+ case 'm':
576
+ return diffMs / 60000;
577
+ case 'h':
578
+ return diffMs / 3600000;
579
+ case 'd':
580
+ return diffMs / 86400000;
581
+ }
582
+ },
583
+
584
+ /**
585
+ * Add time to a date
586
+ */
587
+ add(date: Date, amount: number, unit: 'ms' | 's' | 'm' | 'h' | 'd'): Date {
588
+ const ms = DateTime.diff(new Date(amount), new Date(0), 'ms');
589
+ const multipliers = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
590
+ return new Date(date.getTime() + amount * multipliers[unit]);
591
+ },
592
+
593
+ /**
594
+ * Check if a date is today
595
+ */
596
+ isToday(date: Date): boolean {
597
+ const today = new Date();
598
+ return (
599
+ date.getDate() === today.getDate() &&
600
+ date.getMonth() === today.getMonth() &&
601
+ date.getFullYear() === today.getFullYear()
602
+ );
603
+ },
604
+
605
+ /**
606
+ * Get start of day
607
+ */
608
+ startOfDay(date: Date = new Date()): Date {
609
+ const result = new Date(date);
610
+ result.setHours(0, 0, 0, 0);
611
+ return result;
612
+ },
613
+
614
+ /**
615
+ * Get end of day
616
+ */
617
+ endOfDay(date: Date = new Date()): Date {
618
+ const result = new Date(date);
619
+ result.setHours(23, 59, 59, 999);
620
+ return result;
621
+ },
622
+ };