-
-
Notifications
You must be signed in to change notification settings - Fork 127
/
retro.ts
51 lines (49 loc) · 1.46 KB
/
retro.ts
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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
* An object which can produce a reverse iterator over its values.
*/
export interface IRetroable<T> {
/**
* Get a reverse iterator over the object's values.
*
* @returns An iterator which yields the object's values in reverse.
*/
retro(): IterableIterator<T>;
}
/**
* Create an iterator for a retroable object.
*
* @param object - The retroable or array-like object of interest.
*
* @returns An iterator which traverses the object's values in reverse.
*
* #### Example
* ```typescript
* import { retro } from '@lumino/algorithm';
*
* let data = [1, 2, 3, 4, 5, 6];
*
* let stream = retro(data);
*
* Array.from(stream); // [6, 5, 4, 3, 2, 1]
* ```
*/
export function* retro<T>(
object: IRetroable<T> | ArrayLike<T>
): IterableIterator<T> {
if (typeof (object as IRetroable<T>).retro === 'function') {
yield* (object as IRetroable<T>).retro();
} else {
for (let index = (object as ArrayLike<T>).length - 1; index > -1; index--) {
yield (object as ArrayLike<T>)[index];
}
}
}