-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlazy-evaluation-examples.ts
More file actions
248 lines (216 loc) · 6.19 KB
/
lazy-evaluation-examples.ts
File metadata and controls
248 lines (216 loc) · 6.19 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import {
filter,
filterLazy,
filterLazyAsync,
filterFirst,
filterExists,
filterCount,
filterChunked,
filterLazyChunked,
take,
skip,
map,
toArray,
} from '../src/index';
interface User {
id: number;
name: string;
email: string;
age: number;
city: string;
active: boolean;
premium: boolean;
role: string;
}
const users: User[] = [
{
id: 1,
name: 'Alice',
email: 'alice@example.com',
age: 30,
city: 'Berlin',
active: true,
premium: true,
role: 'admin',
},
{
id: 2,
name: 'Bob',
email: 'bob@example.com',
age: 25,
city: 'London',
active: true,
premium: false,
role: 'user',
},
{
id: 3,
name: 'Charlie',
email: 'charlie@example.com',
age: 35,
city: 'Berlin',
active: false,
premium: true,
role: 'user',
},
{
id: 4,
name: 'David',
email: 'david@example.com',
age: 28,
city: 'Paris',
active: true,
premium: false,
role: 'user',
},
{
id: 5,
name: 'Eve',
email: 'eve@example.com',
age: 32,
city: 'Berlin',
active: true,
premium: true,
role: 'moderator',
},
];
console.log('=== Lazy Evaluation Examples ===\n');
console.log('1. Basic Lazy Filtering');
const lazyFiltered = filterLazy(users, { city: 'Berlin' });
console.log('Lazy iterator created (not executed yet)');
const berlinUsers = toArray(lazyFiltered);
console.log(
'Berlin users:',
berlinUsers.map((u) => u.name),
);
console.log();
console.log('2. Early Exit with filterFirst');
console.log('Standard filter would process all 5 users');
const standardResult = filter(users, { active: true });
console.log('Standard result:', standardResult.length, 'users');
console.log('filterFirst stops after finding 2 matches');
const firstTwo = filterFirst(users, { active: true }, 2);
console.log(
'First 2 active users:',
firstTwo.map((u) => u.name),
);
console.log();
console.log('3. Existence Check with filterExists');
const hasAdmin = filterExists(users, { role: 'admin' });
console.log('Has admin?', hasAdmin);
const hasGuest = filterExists(users, { role: 'guest' });
console.log('Has guest?', hasGuest);
console.log();
console.log('4. Count Matches with filterCount');
const activeCount = filterCount(users, { active: true });
console.log('Active users count:', activeCount);
const premiumCount = filterCount(users, { premium: true });
console.log('Premium users count:', premiumCount);
console.log();
console.log('5. Chunked Processing');
const chunks = filterChunked(users, { active: true }, 2);
console.log('Chunks:', chunks.length);
chunks.forEach((chunk, i) => {
console.log(
` Chunk ${i + 1}:`,
chunk.map((u) => u.name),
);
});
console.log();
console.log('6. Lazy Chunked Processing');
console.log('Processing chunks lazily...');
for (const chunk of filterLazyChunked(users, { active: true }, 2)) {
console.log(
' Processing chunk:',
chunk.map((u) => u.name),
);
}
console.log();
console.log('7. Composing Lazy Operations');
const result = toArray(
take(
map(skip(filterLazy(users, { active: true }), 1), (u) => ({ id: u.id, name: u.name })),
2,
),
);
console.log('Composed result (skip 1, map, take 2):', result);
console.log();
console.log('8. Pagination Example');
function paginate<T>(data: T[], expression: unknown, page: number, pageSize: number) {
return toArray(take(skip(filterLazy(data, expression), page * pageSize), pageSize));
}
const page1 = paginate(users, { active: true }, 0, 2);
console.log(
'Page 1 (2 items):',
page1.map((u) => u.name),
);
const page2 = paginate(users, { active: true }, 1, 2);
console.log(
'Page 2 (2 items):',
page2.map((u) => u.name),
);
console.log();
console.log('9. Async Lazy Filtering');
async function* asyncUsers(): AsyncGenerator<User, void, undefined> {
for (const user of users) {
await new Promise((resolve) => setTimeout(resolve, 10));
yield user;
}
}
(async () => {
console.log('Filtering async stream...');
const asyncFiltered = filterLazyAsync(asyncUsers(), { city: 'Berlin' });
const asyncResult: User[] = [];
for await (const user of asyncFiltered) {
asyncResult.push(user);
}
console.log(
'Async result:',
asyncResult.map((u) => u.name),
);
console.log();
console.log('10. Performance Comparison');
const largeDataset = Array.from({ length: 100000 }, (_, i) => ({
id: i,
name: `User ${i}`,
email: `user${i}@example.com`,
age: 20 + (i % 50),
city: i % 3 === 0 ? 'Berlin' : i % 3 === 1 ? 'London' : 'Paris',
active: i % 2 === 0,
premium: i % 5 === 0,
role: i % 10 === 0 ? 'admin' : 'user',
}));
console.log(`Dataset size: ${largeDataset.length.toLocaleString()} records`);
console.time('Standard filter (all results)');
const standardAll = filter(largeDataset, { city: 'Berlin' });
console.timeEnd('Standard filter (all results)');
console.log(` Found: ${standardAll.length.toLocaleString()} results`);
console.time('filterFirst (first 10)');
const first10 = filterFirst(largeDataset, { city: 'Berlin' }, 10);
console.timeEnd('filterFirst (first 10)');
console.log(` Found: ${first10.length} results`);
console.time('filterExists (existence check)');
const exists = filterExists(largeDataset, { role: 'admin' });
console.timeEnd('filterExists (existence check)');
console.log(` Exists: ${exists}`);
console.time('filterCount (count all)');
const count = filterCount(largeDataset, { city: 'Berlin' });
console.timeEnd('filterCount (count all)');
console.log(` Count: ${count.toLocaleString()}`);
console.log('\n11. Memory Efficiency');
console.log('Standard filter creates array with all results in memory');
console.log('Lazy filter processes items one at a time');
let processedCount = 0;
const lazyResult = filterLazy(largeDataset, (item) => {
processedCount++;
return item.city === 'Berlin';
});
console.log('Lazy iterator created, items processed:', processedCount);
const iterator = lazyResult[Symbol.iterator]();
iterator.next();
iterator.next();
iterator.next();
console.log('After consuming 3 items, total processed:', processedCount);
console.log('(Standard filter would have processed all 100,000 items)');
console.log('\n=== All Examples Completed ===');
})();