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 | import { IIterator, iter, IterableOrArrayLike } from './iter';
|
11 |
|
12 | /**
|
13 | * Take a fixed number of items from an iterable.
|
14 | *
|
15 | * @param object - The iterable or array-like object of interest.
|
16 | *
|
17 | * @param count - The number of items to take from the iterable.
|
18 | *
|
19 | * @returns An iterator which yields the specified number of items
|
20 | * from the source iterable.
|
21 | *
|
22 | * #### Notes
|
23 | * The returned iterator will exhaust early if the source iterable
|
24 | * contains an insufficient number of items.
|
25 | */
|
26 | export function take<T>(
|
27 | object: IterableOrArrayLike<T>,
|
28 | count: number
|
29 | ): IIterator<T> {
|
30 | return new TakeIterator<T>(iter(object), count);
|
31 | }
|
32 |
|
33 | /**
|
34 | * An iterator which takes a fixed number of items from a source.
|
35 | */
|
36 | export class TakeIterator<T> implements IIterator<T> {
|
37 | /**
|
38 | * Construct a new take iterator.
|
39 | *
|
40 | * @param source - The iterator of interest.
|
41 | *
|
42 | * @param count - The number of items to take from the source.
|
43 | */
|
44 | constructor(source: IIterator<T>, count: number) {
|
45 | this._source = source;
|
46 | this._count = count;
|
47 | }
|
48 |
|
49 | /**
|
50 | * Get an iterator over the object's values.
|
51 | *
|
52 | * @returns An iterator which yields the object's values.
|
53 | */
|
54 | iter(): IIterator<T> {
|
55 | return this;
|
56 | }
|
57 |
|
58 | /**
|
59 | * Create an independent clone of the iterator.
|
60 | *
|
61 | * @returns A new independent clone of the iterator.
|
62 | */
|
63 | clone(): IIterator<T> {
|
64 | return new TakeIterator<T>(this._source.clone(), this._count);
|
65 | }
|
66 |
|
67 | /**
|
68 | * Get the next value from the iterator.
|
69 | *
|
70 | * @returns The next value from the iterator, or `undefined`.
|
71 | */
|
72 | next(): T | undefined {
|
73 | if (this._count <= 0) {
|
74 | return undefined;
|
75 | }
|
76 | let value = this._source.next();
|
77 | if (value === undefined) {
|
78 | return undefined;
|
79 | }
|
80 | this._count--;
|
81 | return value;
|
82 | }
|
83 |
|
84 | private _count: number;
|
85 | private _source: IIterator<T>;
|
86 | }
|