-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlazy.ts
More file actions
215 lines (177 loc) · 6.58 KB
/
lazy.ts
File metadata and controls
215 lines (177 loc) · 6.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/**
* Lazy example: Lazy initialization on first access
*
* Demonstrates using Lazy for deferred synchronous initialization.
* Unlike Once, the initialization function is bound at creation time.
*/
import { Lazy, Once } from '../../../src/mod.ts';
// ============================================================================
// Example 1: Basic Lazy usage
// ============================================================================
console.log('=== Example 1: Basic Lazy usage ===\n');
const expensiveValue = Lazy(() => {
console.log('Computing expensive value...');
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += i;
}
return sum;
});
console.log(`Before force: isInitialized = ${expensiveValue.isInitialized()}`);
console.log(`get() = ${expensiveValue.get().isNone() ? 'None' : expensiveValue.get().unwrap()}`);
console.log('\nFirst access via force():');
const result = expensiveValue.force();
console.log(`Result: ${result}`);
console.log('\nSecond access (cached):');
const cached = expensiveValue.force();
console.log(`Result: ${cached} (no computing log)`);
console.log(`isInitialized = ${expensiveValue.isInitialized()}`);
// ============================================================================
// Example 2: Lazy configuration object
// ============================================================================
console.log('\n=== Example 2: Lazy configuration ===\n');
interface AppConfig {
apiUrl: string;
timeout: number;
retries: number;
debug: boolean;
}
const config = Lazy<AppConfig>(() => {
console.log('Loading configuration from file...');
// Simulated config loading
return {
apiUrl: 'https://api.example.com',
timeout: 5000,
retries: 3,
debug: true,
};
});
function getApiUrl(): string {
return config.force().apiUrl;
}
function getTimeout(): number {
return config.force().timeout;
}
// Configuration is loaded on first access
console.log('Calling getApiUrl():');
console.log(`API URL: ${getApiUrl()}`);
console.log('\nCalling getTimeout():');
console.log(`Timeout: ${getTimeout()} (config already loaded, no log)`);
// ============================================================================
// Example 3: Lazy singleton pattern
// ============================================================================
console.log('\n=== Example 3: Lazy singleton pattern ===\n');
class Logger {
private static _instance = Lazy(() => {
console.log('Creating Logger instance...');
return new Logger();
});
// eslint-disable-next-line @typescript-eslint/no-empty-function
private constructor() {}
static get instance(): Logger {
return Logger._instance.force();
}
info(message: string): void {
console.log(`[INFO] ${message}`);
}
error(message: string): void {
console.log(`[ERROR] ${message}`);
}
}
// Logger is created on first access
Logger.instance.info('Application started');
Logger.instance.error('Something went wrong');
Logger.instance.info('But we recovered!');
// ============================================================================
// Example 4: Lazy with expensive computation
// ============================================================================
console.log('\n=== Example 4: Lazy expensive computation ===\n');
// Compute first N prime numbers
const primes = Lazy(() => {
console.log('Computing first 100 prime numbers...');
const result: number[] = [];
let num = 2;
while (result.length < 100) {
let isPrime = true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.push(num);
}
num++;
}
console.log('Done computing primes');
return result;
});
function isPrime(n: number): boolean {
const primeList = primes.force();
if (n <= primeList[primeList.length - 1]) {
return primeList.includes(n);
}
// For larger numbers, do direct check
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
console.log('Checking if 97 is prime:');
console.log(`97 is prime: ${isPrime(97)}`);
console.log('\nChecking if 100 is prime (uses cached primes):');
console.log(`100 is prime: ${isPrime(100)}`);
// ============================================================================
// Example 5: Comparison between Lazy and Once
// ============================================================================
console.log('\n=== Example 5: Lazy vs Once ===\n');
// Lazy: initialization function bound at creation
const lazyValue = Lazy(() => {
console.log('Lazy: Computing value');
return 42;
});
// Once: initialization function provided at access time
const onceValue = Once<number>();
console.log('With Lazy:');
console.log(` First access: ${lazyValue.force()}`);
console.log(` Second access: ${lazyValue.force()} (cached)`);
console.log('\nWith Once:');
// Can use different functions - only first one runs
const v1 = onceValue.getOrInit(() => {
console.log('Once: Computing first value');
return 100;
});
const v2 = onceValue.getOrInit(() => {
console.log('Once: Computing second value (never called)');
return 200;
});
console.log(` First getOrInit: ${v1}`);
console.log(` Second getOrInit: ${v2} (returns cached value)`);
console.log('\nKey differences:');
console.log(' - Lazy: Function bound at creation, simpler API (just force())');
console.log(' - Once: Function provided at access, more flexible (getOrInit, set, take)');
// ============================================================================
// Example 6: Lazy with error handling
// ============================================================================
console.log('\n=== Example 6: Lazy with error handling ===\n');
const shouldFail = true;
const riskyValue = Lazy(() => {
console.log('Attempting to compute value...');
if (shouldFail) {
throw new Error('Computation failed!');
}
return 'Success!';
});
console.log('First attempt (will fail):');
try {
riskyValue.force();
} catch (e) {
console.log(`Error: ${(e as Error).message}`);
console.log(`isInitialized: ${riskyValue.isInitialized()}`);
}
console.log('\nNote: After error, Lazy is still uninitialized.');
console.log('Unlike Once, Lazy will retry initialization on next force().');
// In real code, you might create a new Lazy or handle differently
// For demo purposes, we'll just show the state
console.log(`Final isInitialized: ${riskyValue.isInitialized()}`);