Debian Codegraph @

node/rxjs/src/internal/observable/generate.ts

raw
1 import { Observable } from '../Observable';
2 import { identity } from '../util/identity';
3 import { ObservableInput, SchedulerLike } from '../types';
4 import { isScheduler } from '../util/isScheduler';
5 import { defer } from './defer';
6 import { scheduleIterable } from '../scheduled/scheduleIterable';
7
8 type ConditionFunc<S> = (state: S) => boolean;
9 type IterateFunc<S> = (state: S) => S;
10 type ResultFunc<S, T> = (state: S) => T;
11
12 export interface GenerateBaseOptions<S> {
13 /**
14 * Initial state.
15 */
16 initialState: S;
17 /**
18 * Condition function that accepts state and returns boolean.
19 * When it returns false, the generator stops.
20 * If not specified, a generator never stops.
21 */
22 condition?: ConditionFunc<S>;
23 /**
24 * Iterate function that accepts state and returns new state.
25 */
26 iterate: IterateFunc<S>;
27 /**
28 * SchedulerLike to use for generation process.
29 * By default, a generator starts immediately.
30 */
31 scheduler?: SchedulerLike;
32 }
33
34 export interface GenerateOptions<T, S> extends GenerateBaseOptions<S> {
35 /**
36 * Result selection function that accepts state and returns a value to emit.
37 */
38 resultSelector: ResultFunc<S, T>;
39 }
40
41 /**
42 * Generates an observable sequence by running a state-driven loop
43 * producing the sequence's elements, using the specified scheduler
44 * to send out observer messages.
45 *
46 * ![](generate.png)
47 *
48 * ## Examples
49 *
50 * Produces sequence of numbers
51 *
52 * ```ts
53 * import { generate } from 'rxjs';
54 *
55 * const result = generate(0, x => x < 3, x => x + 1, x => x);
56 *
57 * result.subscribe(x => console.log(x));
58 *
59 * // Logs:
60 * // 0
61 * // 1
62 * // 2
63 * ```
64 *
65 * Use `asapScheduler`
66 *
67 * ```ts
68 * import { generate, asapScheduler } from 'rxjs';
69 *
70 * const result = generate(1, x => x < 5, x => x * 2, x => x + 1, asapScheduler);
71 *
72 * result.subscribe(x => console.log(x));
73 *
74 * // Logs:
75 * // 2
76 * // 3
77 * // 5
78 * ```
79 *
80 * @see {@link from}
81 * @see {@link Observable}
82 *
83 * @param initialState Initial state.
84 * @param condition Condition to terminate generation (upon returning false).
85 * @param iterate Iteration step function.
86 * @param resultSelector Selector function for results produced in the sequence.
87 * @param scheduler A {@link SchedulerLike} on which to run the generator loop.
88 * If not provided, defaults to emit immediately.
89 * @returns The generated sequence.
90 * @deprecated Instead of passing separate arguments, use the options argument.
91 * Signatures taking separate arguments will be removed in v8.
92 */
93 export function generate<T, S>(
94 initialState: S,
95 condition: ConditionFunc<S>,
96 iterate: IterateFunc<S>,
97 resultSelector: ResultFunc<S, T>,
98 scheduler?: SchedulerLike
99 ): Observable<T>;
100
101 /**
102 * Generates an Observable by running a state-driven loop
103 * that emits an element on each iteration.
104 *
105 * <span class="informal">Use it instead of nexting values in a for loop.</span>
106 *
107 * ![](generate.png)
108 *
109 * `generate` allows you to create a stream of values generated with a loop very similar to
110 * a traditional for loop. The first argument of `generate` is a beginning value. The second argument
111 * is a function that accepts this value and tests if some condition still holds. If it does,
112 * then the loop continues, if not, it stops. The third value is a function which takes the
113 * previously defined value and modifies it in some way on each iteration. Note how these three parameters
114 * are direct equivalents of three expressions in a traditional for loop: the first expression
115 * initializes some state (for example, a numeric index), the second tests if the loop can perform the next
116 * iteration (for example, if the index is lower than 10) and the third states how the defined value
117 * will be modified on every step (for example, the index will be incremented by one).
118 *
119 * Return value of a `generate` operator is an Observable that on each loop iteration
120 * emits a value. First of all, the condition function is ran. If it returns true, then the Observable
121 * emits the currently stored value (initial value at the first iteration) and finally updates
122 * that value with iterate function. If at some point the condition returns false, then the Observable
123 * completes at that moment.
124 *
125 * Optionally you can pass a fourth parameter to `generate` - a result selector function which allows you
126 * to immediately map the value that would normally be emitted by an Observable.
127 *
128 * If you find three anonymous functions in `generate` call hard to read, you can provide
129 * a single object to the operator instead where the object has the properties: `initialState`,
130 * `condition`, `iterate` and `resultSelector`, which should have respective values that you
131 * would normally pass to `generate`. `resultSelector` is still optional, but that form
132 * of calling `generate` allows you to omit `condition` as well. If you omit it, that means
133 * condition always holds, or in other words the resulting Observable will never complete.
134 *
135 * Both forms of `generate` can optionally accept a scheduler. In case of a multi-parameter call,
136 * scheduler simply comes as a last argument (no matter if there is a `resultSelector`
137 * function or not). In case of a single-parameter call, you can provide it as a
138 * `scheduler` property on the object passed to the operator. In both cases, a scheduler decides when
139 * the next iteration of the loop will happen and therefore when the next value will be emitted
140 * by the Observable. For example, to ensure that each value is pushed to the Observer
141 * on a separate task in the event loop, you could use the `async` scheduler. Note that
142 * by default (when no scheduler is passed) values are simply emitted synchronously.
143 *
144 *
145 * ## Examples
146 *
147 * Use with condition and iterate functions
148 *
149 * ```ts
150 * import { generate } from 'rxjs';
151 *
152 * const result = generate(0, x => x < 3, x => x + 1);
153 *
154 * result.subscribe({
155 * next: value => console.log(value),
156 * complete: () => console.log('Complete!')
157 * });
158 *
159 * // Logs:
160 * // 0
161 * // 1
162 * // 2
163 * // 'Complete!'
164 * ```
165 *
166 * Use with condition, iterate and resultSelector functions
167 *
168 * ```ts
169 * import { generate } from 'rxjs';
170 *
171 * const result = generate(0, x => x < 3, x => x + 1, x => x * 1000);
172 *
173 * result.subscribe({
174 * next: value => console.log(value),
175 * complete: () => console.log('Complete!')
176 * });
177 *
178 * // Logs:
179 * // 0
180 * // 1000
181 * // 2000
182 * // 'Complete!'
183 * ```
184 *
185 * Use with options object
186 *
187 * ```ts
188 * import { generate } from 'rxjs';
189 *
190 * const result = generate({
191 * initialState: 0,
192 * condition(value) { return value < 3; },
193 * iterate(value) { return value + 1; },
194 * resultSelector(value) { return value * 1000; }
195 * });
196 *
197 * result.subscribe({
198 * next: value => console.log(value),
199 * complete: () => console.log('Complete!')
200 * });
201 *
202 * // Logs:
203 * // 0
204 * // 1000
205 * // 2000
206 * // 'Complete!'
207 * ```
208 *
209 * Use options object without condition function
210 *
211 * ```ts
212 * import { generate } from 'rxjs';
213 *
214 * const result = generate({
215 * initialState: 0,
216 * iterate(value) { return value + 1; },
217 * resultSelector(value) { return value * 1000; }
218 * });
219 *
220 * result.subscribe({
221 * next: value => console.log(value),
222 * complete: () => console.log('Complete!') // This will never run
223 * });
224 *
225 * // Logs:
226 * // 0
227 * // 1000
228 * // 2000
229 * // 3000
230 * // ...and never stops.
231 * ```
232 *
233 * @see {@link from}
234 *
235 * @param initialState Initial state.
236 * @param condition Condition to terminate generation (upon returning false).
237 * @param iterate Iteration step function.
238 * @param scheduler A {@link Scheduler} on which to run the generator loop. If not
239 * provided, defaults to emitting immediately.
240 * @return The generated sequence.
241 * @deprecated Instead of passing separate arguments, use the options argument.
242 * Signatures taking separate arguments will be removed in v8.
243 */
244 export function generate<S>(
245 initialState: S,
246 condition: ConditionFunc<S>,
247 iterate: IterateFunc<S>,
248 scheduler?: SchedulerLike
249 ): Observable<S>;
250
251 /**
252 * Generates an observable sequence by running a state-driven loop
253 * producing the sequence's elements, using the specified scheduler
254 * to send out observer messages.
255 * The overload accepts options object that might contain initial state, iterate,
256 * condition and scheduler.
257 *
258 * ![](generate.png)
259 *
260 * ## Examples
261 *
262 * Use options object with condition function
263 *
264 * ```ts
265 * import { generate } from 'rxjs';
266 *
267 * const result = generate({
268 * initialState: 0,
269 * condition: x => x < 3,
270 * iterate: x => x + 1
271 * });
272 *
273 * result.subscribe({
274 * next: value => console.log(value),
275 * complete: () => console.log('Complete!')
276 * });
277 *
278 * // Logs:
279 * // 0
280 * // 1
281 * // 2
282 * // 'Complete!'
283 * ```
284 *
285 * @see {@link from}
286 * @see {@link Observable}
287 *
288 * @param options Object that must contain initialState, iterate and might contain condition and scheduler.
289 * @returns The generated sequence.
290 */
291 export function generate<S>(options: GenerateBaseOptions<S>): Observable<S>;
292
293 /**
294 * Generates an observable sequence by running a state-driven loop
295 * producing the sequence's elements, using the specified scheduler
296 * to send out observer messages.
297 * The overload accepts options object that might contain initial state, iterate,
298 * condition, result selector and scheduler.
299 *
300 * ![](generate.png)
301 *
302 * ## Examples
303 *
304 * Use options object with condition and iterate function
305 *
306 * ```ts
307 * import { generate } from 'rxjs';
308 *
309 * const result = generate({
310 * initialState: 0,
311 * condition: x => x < 3,
312 * iterate: x => x + 1,
313 * resultSelector: x => x
314 * });
315 *
316 * result.subscribe({
317 * next: value => console.log(value),
318 * complete: () => console.log('Complete!')
319 * });
320 *
321 * // Logs:
322 * // 0
323 * // 1
324 * // 2
325 * // 'Complete!'
326 * ```
327 *
328 * @see {@link from}
329 * @see {@link Observable}
330 *
331 * @param options Object that must contain initialState, iterate, resultSelector and might contain condition and scheduler.
332 * @returns The generated sequence.
333 */
334 export function generate<T, S>(options: GenerateOptions<T, S>): Observable<T>;
335
336 export function generate<T, S>(
337 initialStateOrOptions: S | GenerateOptions<T, S>,
338 condition?: ConditionFunc<S>,
339 iterate?: IterateFunc<S>,
340 resultSelectorOrScheduler?: ResultFunc<S, T> | SchedulerLike,
341 scheduler?: SchedulerLike
342 ): Observable<T> {
343 let resultSelector: ResultFunc<S, T>;
344 let initialState: S;
345
346 // TODO: Remove this as we move away from deprecated signatures
347 // and move towards a configuration object argument.
348 if (arguments.length === 1) {
349 // If we only have one argument, we can assume it is a configuration object.
350 // Note that folks not using TypeScript may trip over this.
351 ({
352 initialState,
353 condition,
354 iterate,
355 resultSelector = identity as ResultFunc<S, T>,
356 scheduler,
357 } = initialStateOrOptions as GenerateOptions<T, S>);
358 } else {
359 // Deprecated arguments path. Figure out what the user
360 // passed and set it here.
361 initialState = initialStateOrOptions as S;
362 if (!resultSelectorOrScheduler || isScheduler(resultSelectorOrScheduler)) {
363 resultSelector = identity as ResultFunc<S, T>;
364 scheduler = resultSelectorOrScheduler as SchedulerLike;
365 } else {
366 resultSelector = resultSelectorOrScheduler as ResultFunc<S, T>;
367 }
368 }
369
370 // The actual generator used to "generate" values.
371 function* gen() {
372 for (let state = initialState; !condition || condition(state); state = iterate!(state)) {
373 yield resultSelector(state);
374 }
375 }
376
377 // We use `defer` because we want to defer the creation of the iterator from the iterable.
378 return defer(
379 (scheduler
380 ? // If a scheduler was provided, use `scheduleIterable` to ensure that iteration/generation
381 // happens on the scheduler.
382 () => scheduleIterable(gen(), scheduler!)
383 : // Otherwise, if there's no scheduler, we can just use the generator function directly in
384 // `defer` and executing it will return the generator (which is iterable).
385 gen) as () => ObservableInput<T>
386 );
387 }