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 | |----------------------------------------------------------------------------*/
|
10 |
|
11 | /**
|
12 | * Take a fixed number of items from an iterable.
|
13 | *
|
14 | * @param object - The iterable object of interest.
|
15 | *
|
16 | * @param count - The number of items to take from the iterable.
|
17 | *
|
18 | * @returns An iterator which yields the specified number of items
|
19 | * from the source iterable.
|
20 | *
|
21 | * #### Notes
|
22 | * The returned iterator will exhaust early if the source iterable
|
23 | * contains an insufficient number of items.
|
24 | *
|
25 | * #### Example
|
26 | * ```typescript
|
27 | * import { take } from '@lumino/algorithm';
|
28 | *
|
29 | * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);
|
30 | *
|
31 | * Array.from(stream); // [5, 4, 3]
|
32 | * ```
|
33 | */
|
34 | export function* take<T>(
|
35 | object: Iterable<T>,
|
36 | count: number
|
37 | ): IterableIterator<T> {
|
38 | if (count < 1) {
|
39 | return;
|
40 | }
|
41 | const it = object[Symbol.iterator]();
|
42 | let item: IteratorResult<T>;
|
43 | while (0 < count-- && !(item = it.next()).done) {
|
44 | yield item.value;
|
45 | }
|
46 | }
|