UNPKG

2.65 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
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|----------------------------------------------------------------------------*/
10var iter_1 = require("./iter");
11/**
12 * Filter an iterable for values which pass a test.
13 *
14 * @param object - The iterable or array-like object of interest.
15 *
16 * @param fn - The predicate function to invoke for each value.
17 *
18 * @returns An iterator which yields the values which pass the test.
19 *
20 * #### Example
21 * ```typescript
22 * import { filter, toArray } from '@phosphor/algorithm';
23 *
24 * let data = [1, 2, 3, 4, 5, 6];
25 *
26 * let stream = filter(data, value => value % 2 === 0);
27 *
28 * toArray(stream); // [2, 4, 6]
29 * ```
30 */
31function filter(object, fn) {
32 return new FilterIterator(iter_1.iter(object), fn);
33}
34exports.filter = filter;
35/**
36 * An iterator which yields values which pass a test.
37 */
38var FilterIterator = /** @class */ (function () {
39 /**
40 * Construct a new filter iterator.
41 *
42 * @param source - The iterator of values of interest.
43 *
44 * @param fn - The predicate function to invoke for each value.
45 */
46 function FilterIterator(source, fn) {
47 this._index = 0;
48 this._source = source;
49 this._fn = fn;
50 }
51 /**
52 * Get an iterator over the object's values.
53 *
54 * @returns An iterator which yields the object's values.
55 */
56 FilterIterator.prototype.iter = function () {
57 return this;
58 };
59 /**
60 * Create an independent clone of the iterator.
61 *
62 * @returns A new independent clone of the iterator.
63 */
64 FilterIterator.prototype.clone = function () {
65 var result = new FilterIterator(this._source.clone(), this._fn);
66 result._index = this._index;
67 return result;
68 };
69 /**
70 * Get the next value from the iterator.
71 *
72 * @returns The next value from the iterator, or `undefined`.
73 */
74 FilterIterator.prototype.next = function () {
75 var fn = this._fn;
76 var it = this._source;
77 var value;
78 while ((value = it.next()) !== undefined) {
79 if (fn(value, this._index++)) {
80 return value;
81 }
82 }
83 return undefined;
84 };
85 return FilterIterator;
86}());
87exports.FilterIterator = FilterIterator;