UNPKG

2.53 kBPlain TextView Raw
1// Copyright (c) Jupyter Development Team.
2// Distributed under the terms of the Modified BSD License.
3/*-----------------------------------------------------------------------------
4| Copyright (c) 2014-2017, PhosphorJS Contributors
5|
6| Distributed under the terms of the BSD 3-Clause License.
7|
8| The full license is in the file LICENSE, distributed with this software.
9|----------------------------------------------------------------------------*/
10import { IIterator } from './iter';
11
12/**
13 * Create an iterator which repeats a value a number of times.
14 *
15 * @param value - The value to repeat.
16 *
17 * @param count - The number of times to repeat the value.
18 *
19 * @returns A new iterator which repeats the specified value.
20 *
21 * #### Example
22 * ```typescript
23 * import { repeat, toArray } from '@lumino/algorithm';
24 *
25 * let stream = repeat(7, 3);
26 *
27 * toArray(stream); // [7, 7, 7]
28 * ```
29 */
30export function repeat<T>(value: T, count: number): IIterator<T> {
31 return new RepeatIterator<T>(value, count);
32}
33
34/**
35 * Create an iterator which yields a value a single time.
36 *
37 * @param value - The value to wrap in an iterator.
38 *
39 * @returns A new iterator which yields the value a single time.
40 *
41 * #### Example
42 * ```typescript
43 * import { once, toArray } from '@lumino/algorithm';
44 *
45 * let stream = once(7);
46 *
47 * toArray(stream); // [7]
48 * ```
49 */
50export function once<T>(value: T): IIterator<T> {
51 return new RepeatIterator<T>(value, 1);
52}
53
54/**
55 * An iterator which repeats a value a specified number of times.
56 */
57export class RepeatIterator<T> implements IIterator<T> {
58 /**
59 * Construct a new repeat iterator.
60 *
61 * @param value - The value to repeat.
62 *
63 * @param count - The number of times to repeat the value.
64 */
65 constructor(value: T, count: number) {
66 this._value = value;
67 this._count = count;
68 }
69
70 /**
71 * Get an iterator over the object's values.
72 *
73 * @returns An iterator which yields the object's values.
74 */
75 iter(): IIterator<T> {
76 return this;
77 }
78
79 /**
80 * Create an independent clone of the iterator.
81 *
82 * @returns A new independent clone of the iterator.
83 */
84 clone(): IIterator<T> {
85 return new RepeatIterator<T>(this._value, this._count);
86 }
87
88 /**
89 * Get the next value from the iterator.
90 *
91 * @returns The next value from the iterator, or `undefined`.
92 */
93 next(): T | undefined {
94 if (this._count <= 0) {
95 return undefined;
96 }
97 this._count--;
98 return this._value;
99 }
100
101 private _value: T;
102 private _count: number;
103}