zhangjian
2023-05-30 dabbcc356af21f9f2f88ac69ff07994e6e32e4fc
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import { Observable } from '../Observable';
import { identity } from '../util/identity';
import { ObservableInput, SchedulerLike } from '../types';
import { isScheduler } from '../util/isScheduler';
import { defer } from './defer';
import { scheduleIterable } from '../scheduled/scheduleIterable';
 
type ConditionFunc<S> = (state: S) => boolean;
type IterateFunc<S> = (state: S) => S;
type ResultFunc<S, T> = (state: S) => T;
 
export interface GenerateBaseOptions<S> {
  /**
   * Initial state.
   */
  initialState: S;
  /**
   * Condition function that accepts state and returns boolean.
   * When it returns false, the generator stops.
   * If not specified, a generator never stops.
   */
  condition?: ConditionFunc<S>;
  /**
   * Iterate function that accepts state and returns new state.
   */
  iterate: IterateFunc<S>;
  /**
   * SchedulerLike to use for generation process.
   * By default, a generator starts immediately.
   */
  scheduler?: SchedulerLike;
}
 
export interface GenerateOptions<T, S> extends GenerateBaseOptions<S> {
  /**
   * Result selection function that accepts state and returns a value to emit.
   */
  resultSelector: ResultFunc<S, T>;
}
 
/**
 * Generates an observable sequence by running a state-driven loop
 * producing the sequence's elements, using the specified scheduler
 * to send out observer messages.
 *
 * ![](generate.png)
 *
 * ## Examples
 *
 * Produces sequence of numbers
 *
 * ```ts
 * import { generate } from 'rxjs';
 *
 * const result = generate(0, x => x < 3, x => x + 1, x => x);
 *
 * result.subscribe(x => console.log(x));
 *
 * // Logs:
 * // 0
 * // 1
 * // 2
 * ```
 *
 * Use `asapScheduler`
 *
 * ```ts
 * import { generate, asapScheduler } from 'rxjs';
 *
 * const result = generate(1, x => x < 5, x => x * 2, x => x + 1, asapScheduler);
 *
 * result.subscribe(x => console.log(x));
 *
 * // Logs:
 * // 2
 * // 3
 * // 5
 * ```
 *
 * @see {@link from}
 * @see {@link Observable}
 *
 * @param {S} initialState Initial state.
 * @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false).
 * @param {function (state: S): S} iterate Iteration step function.
 * @param {function (state: S): T} resultSelector Selector function for results produced in the sequence. (deprecated)
 * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} on which to run the generator loop. If not provided, defaults to emit immediately.
 * @returns {Observable<T>} The generated sequence.
 * @deprecated Instead of passing separate arguments, use the options argument. Signatures taking separate arguments will be removed in v8.
 */
export function generate<T, S>(
  initialState: S,
  condition: ConditionFunc<S>,
  iterate: IterateFunc<S>,
  resultSelector: ResultFunc<S, T>,
  scheduler?: SchedulerLike
): Observable<T>;
 
/**
 * Generates an Observable by running a state-driven loop
 * that emits an element on each iteration.
 *
 * <span class="informal">Use it instead of nexting values in a for loop.</span>
 *
 * ![](generate.png)
 *
 * `generate` allows you to create a stream of values generated with a loop very similar to
 * a traditional for loop. The first argument of `generate` is a beginning value. The second argument
 * is a function that accepts this value and tests if some condition still holds. If it does,
 * then the loop continues, if not, it stops. The third value is a function which takes the
 * previously defined value and modifies it in some way on each iteration. Note how these three parameters
 * are direct equivalents of three expressions in a traditional for loop: the first expression
 * initializes some state (for example, a numeric index), the second tests if the loop can perform the next
 * iteration (for example, if the index is lower than 10) and the third states how the defined value
 * will be modified on every step (for example, the index will be incremented by one).
 *
 * Return value of a `generate` operator is an Observable that on each loop iteration
 * emits a value. First of all, the condition function is ran. If it returns true, then the Observable
 * emits the currently stored value (initial value at the first iteration) and finally updates
 * that value with iterate function. If at some point the condition returns false, then the Observable
 * completes at that moment.
 *
 * Optionally you can pass a fourth parameter to `generate` - a result selector function which allows you
 * to immediately map the value that would normally be emitted by an Observable.
 *
 * If you find three anonymous functions in `generate` call hard to read, you can provide
 * a single object to the operator instead where the object has the properties: `initialState`,
 * `condition`, `iterate` and `resultSelector`, which should have respective values that you
 * would normally pass to `generate`. `resultSelector` is still optional, but that form
 * of calling `generate` allows you to omit `condition` as well. If you omit it, that means
 * condition always holds, or in other words the resulting Observable will never complete.
 *
 * Both forms of `generate` can optionally accept a scheduler. In case of a multi-parameter call,
 * scheduler simply comes as a last argument (no matter if there is a `resultSelector`
 * function or not). In case of a single-parameter call, you can provide it as a
 * `scheduler` property on the object passed to the operator. In both cases, a scheduler decides when
 * the next iteration of the loop will happen and therefore when the next value will be emitted
 * by the Observable. For example, to ensure that each value is pushed to the Observer
 * on a separate task in the event loop, you could use the `async` scheduler. Note that
 * by default (when no scheduler is passed) values are simply emitted synchronously.
 *
 *
 * ## Examples
 *
 * Use with condition and iterate functions
 *
 * ```ts
 * import { generate } from 'rxjs';
 *
 * const result = generate(0, x => x < 3, x => x + 1);
 *
 * result.subscribe({
 *   next: value => console.log(value),
 *   complete: () => console.log('Complete!')
 * });
 *
 * // Logs:
 * // 0
 * // 1
 * // 2
 * // 'Complete!'
 * ```
 *
 * Use with condition, iterate and resultSelector functions
 *
 * ```ts
 * import { generate } from 'rxjs';
 *
 * const result = generate(0, x => x < 3, x => x + 1, x => x * 1000);
 *
 * result.subscribe({
 *   next: value => console.log(value),
 *   complete: () => console.log('Complete!')
 * });
 *
 * // Logs:
 * // 0
 * // 1000
 * // 2000
 * // 'Complete!'
 * ```
 *
 * Use with options object
 *
 * ```ts
 * import { generate } from 'rxjs';
 *
 * const result = generate({
 *   initialState: 0,
 *   condition(value) { return value < 3; },
 *   iterate(value) { return value + 1; },
 *   resultSelector(value) { return value * 1000; }
 * });
 *
 * result.subscribe({
 *   next: value => console.log(value),
 *   complete: () => console.log('Complete!')
 * });
 *
 * // Logs:
 * // 0
 * // 1000
 * // 2000
 * // 'Complete!'
 * ```
 *
 * Use options object without condition function
 *
 * ```ts
 * import { generate } from 'rxjs';
 *
 * const result = generate({
 *   initialState: 0,
 *   iterate(value) { return value + 1; },
 *   resultSelector(value) { return value * 1000; }
 * });
 *
 * result.subscribe({
 *   next: value => console.log(value),
 *   complete: () => console.log('Complete!') // This will never run
 * });
 *
 * // Logs:
 * // 0
 * // 1000
 * // 2000
 * // 3000
 * // ...and never stops.
 * ```
 *
 * @see {@link from}
 *
 * @param {S} initialState Initial state.
 * @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false).
 * @param {function (state: S): S} iterate Iteration step function.
 * @param {function (state: S): T} [resultSelector] Selector function for results produced in the sequence.
 * @param {Scheduler} [scheduler] A {@link Scheduler} on which to run the generator loop. If not provided, defaults to emitting immediately.
 * @return {Observable<T>} The generated sequence.
 * @deprecated Instead of passing separate arguments, use the options argument. Signatures taking separate arguments will be removed in v8.
 */
export function generate<S>(
  initialState: S,
  condition: ConditionFunc<S>,
  iterate: IterateFunc<S>,
  scheduler?: SchedulerLike
): Observable<S>;
 
/**
 * Generates an observable sequence by running a state-driven loop
 * producing the sequence's elements, using the specified scheduler
 * to send out observer messages.
 * The overload accepts options object that might contain initial state, iterate,
 * condition and scheduler.
 *
 * ![](generate.png)
 *
 * ## Examples
 *
 * Use options object with condition function
 *
 * ```ts
 * import { generate } from 'rxjs';
 *
 * const result = generate({
 *   initialState: 0,
 *   condition: x => x < 3,
 *   iterate: x => x + 1
 * });
 *
 * result.subscribe({
 *   next: value => console.log(value),
 *   complete: () => console.log('Complete!')
 * });
 *
 * // Logs:
 * // 0
 * // 1
 * // 2
 * // 'Complete!'
 * ```
 *
 * @see {@link from}
 * @see {@link Observable}
 *
 * @param {GenerateBaseOptions<S>} options Object that must contain initialState, iterate and might contain condition and scheduler.
 * @returns {Observable<S>} The generated sequence.
 */
export function generate<S>(options: GenerateBaseOptions<S>): Observable<S>;
 
/**
 * Generates an observable sequence by running a state-driven loop
 * producing the sequence's elements, using the specified scheduler
 * to send out observer messages.
 * The overload accepts options object that might contain initial state, iterate,
 * condition, result selector and scheduler.
 *
 * ![](generate.png)
 *
 * ## Examples
 *
 * Use options object with condition and iterate function
 *
 * ```ts
 * import { generate } from 'rxjs';
 *
 * const result = generate({
 *   initialState: 0,
 *   condition: x => x < 3,
 *   iterate: x => x + 1,
 *   resultSelector: x => x
 * });
 *
 * result.subscribe({
 *   next: value => console.log(value),
 *   complete: () => console.log('Complete!')
 * });
 *
 * // Logs:
 * // 0
 * // 1
 * // 2
 * // 'Complete!'
 * ```
 *
 * @see {@link from}
 * @see {@link Observable}
 *
 * @param {GenerateOptions<T, S>} options Object that must contain initialState, iterate, resultSelector and might contain condition and scheduler.
 * @returns {Observable<T>} The generated sequence.
 */
export function generate<T, S>(options: GenerateOptions<T, S>): Observable<T>;
 
export function generate<T, S>(
  initialStateOrOptions: S | GenerateOptions<T, S>,
  condition?: ConditionFunc<S>,
  iterate?: IterateFunc<S>,
  resultSelectorOrScheduler?: ResultFunc<S, T> | SchedulerLike,
  scheduler?: SchedulerLike
): Observable<T> {
  let resultSelector: ResultFunc<S, T>;
  let initialState: S;
 
  // TODO: Remove this as we move away from deprecated signatures
  // and move towards a configuration object argument.
  if (arguments.length === 1) {
    // If we only have one argument, we can assume it is a configuration object.
    // Note that folks not using TypeScript may trip over this.
    ({
      initialState,
      condition,
      iterate,
      resultSelector = identity as ResultFunc<S, T>,
      scheduler,
    } = initialStateOrOptions as GenerateOptions<T, S>);
  } else {
    // Deprecated arguments path. Figure out what the user
    // passed and set it here.
    initialState = initialStateOrOptions as S;
    if (!resultSelectorOrScheduler || isScheduler(resultSelectorOrScheduler)) {
      resultSelector = identity as ResultFunc<S, T>;
      scheduler = resultSelectorOrScheduler as SchedulerLike;
    } else {
      resultSelector = resultSelectorOrScheduler as ResultFunc<S, T>;
    }
  }
 
  // The actual generator used to "generate" values.
  function* gen() {
    for (let state = initialState; !condition || condition(state); state = iterate!(state)) {
      yield resultSelector(state);
    }
  }
 
  // We use `defer` because we want to defer the creation of the iterator from the iterable.
  return defer(
    (scheduler
      ? // If a scheduler was provided, use `scheduleIterable` to ensure that iteration/generation
        // happens on the scheduler.
        () => scheduleIterable(gen(), scheduler!)
      : // Otherwise, if there's no scheduler, we can just use the generator function directly in
        // `defer` and executing it will return the generator (which is iterable).
        gen) as () => ObservableInput<T>
  );
}