UNPKG

itertools-ts

Version:

Extended itertools port for TypeScript and JavaScript. Provides a huge set of functions for working with iterable collections (including async ones)

952 lines 30.1 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __asyncValues = (this && this.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; import { teeAsync, toArrayAsync, toAsyncIterable, toMapAsync, toSetAsync, } from "./transform"; import { chunkwiseAsync, chunkwiseOverlapAsync, compressAsync, dropWhileAsync, enumerateAsync, filterAsync, flatMapAsync, flattenAsync, groupByAsync, keysAsync, limitAsync, mapAsync, pairwiseAsync, skipAsync, sliceAsync, sortAsync, takeWhileAsync, valuesAsync, } from "./single"; import { chainAsync, zipAsync, zipEqualAsync, zipFilledAsync, zipLongestAsync, } from "./multi"; import { runningAverageAsync, runningDifferenceAsync, runningMaxAsync, runningMinAsync, runningProductAsync, runningTotalAsync, } from "./math"; import { distinctAsync, intersectionAsync, partialIntersectionAsync, symmetricDifferenceAsync, unionAsync, } from "./set"; import { cartesianProductAsync, combinationsAsync, permutationsAsync, } from "./combinatorics"; import { toAverageAsync, toCountAsync, toFirstAndLastAsync, toFirstAsync, toLastAsync, toMaxAsync, toMinAsync, toMinMaxAsync, toProductAsync, toRangeAsync, toSumAsync, toValueAsync, } from "./reduce"; import { allMatchAsync, allUniqueAsync, anyMatchAsync, exactlyNAsync, isReversedAsync, isSortedAsync, noneMatchAsync, sameAsync, sameCountAsync, } from "./summary"; import { infinite } from "./index"; /** * Provides fluent interface for working with async iterables. */ export class AsyncStream { /** * Creates iterable instance with fluent interface. * * @param data */ static of(data) { return new AsyncStream(toAsyncIterable(data)); } /** * Creates iterable instance with fluent interface from empty iterable source. */ static ofEmpty() { return new AsyncStream(toAsyncIterable([])); } /** * Creates iterable instance with fluent interface from infinite count iterable. * * @param start (optional, default 1) * @param step (optional, default 1) */ static ofCount(start = 1, step = 1) { return new AsyncStream(toAsyncIterable(infinite.count(start, step))); } /** * Creates iterable instance with fluent interface from infinite collection items repeating. * * @param iterable */ static ofCycle(iterable) { return new AsyncStream(infinite.cycleAsync(iterable)); } /** * Creates iterable instance with fluent interface from infinite item repeating. * * @param item */ static ofRepeat(item) { return new AsyncStream(toAsyncIterable(infinite.repeat(item))); } /** * Iterate stream collection with another iterable collections simultaneously. * * Make an iterator that aggregates items from multiple iterators. * Similar to Python's zip function. * * For uneven lengths, iterations stops when the shortest iterable is exhausted. * * @param iterables * * @see multi.zipAsync */ zipWith(...iterables) { this.data = zipAsync(this.data, ...iterables); return this; } /** * Iterate stream collection with another iterable collections simultaneously. * * Make an iterator that aggregates items from multiple iterators. * Similar to Python's zip_longest function. * * Iteration continues until the longest iterable is exhausted. * For uneven lengths, the exhausted iterables will produce `filler` value for the remaining iterations. * * @param filler * @param iterables * * @see multi.zipLongestAsync */ zipFilledWith(filler, ...iterables) { this.data = zipFilledAsync(filler, this.data, ...iterables); return this; } /** * Iterate stream collection with another iterable collections simultaneously. * * Make an iterator that aggregates items from multiple iterators. * Similar to Python's zip_longest function. * * Iteration continues until the longest iterable is exhausted. * For uneven lengths, the exhausted iterables will produce `undefined` for the remaining iterations. * * @param iterables * * @see multi.zipLongestAsync */ zipLongestWith(...iterables) { this.data = zipLongestAsync(this.data, ...iterables); return this; } /** * Iterate stream collection with another iterable collections of equal lengths simultaneously. * * Works like multi.zip() method but throws LengthException if lengths not equal, * i.e., at least one iterator ends before the others. * * @param iterables * * @see multi.zipEqualAsync */ zipEqualWith(...iterables) { this.data = zipEqualAsync(this.data, ...iterables); return this; } /** * Chain stream collection withs given iterables together into a single iteration. * * Makes a single continuous sequence out of multiple sequences. * * @param iterables * * @see multi.chainAsync */ chainWith(...iterables) { this.data = chainAsync(this.data, ...iterables); return this; } /** * Return overlapped chunks of elements from iterable source. * * Chunk size must be at least 1. * * Overlap size must be less than chunk size. * * @param chunkSize * @param overlapSize * @param includeIncompleteTail * * @see single.chunkwiseOverlapAsync */ chunkwiseOverlap(chunkSize, overlapSize, includeIncompleteTail = true) { this.data = chunkwiseOverlapAsync(this.data, chunkSize, overlapSize, includeIncompleteTail); return this; } /** * Return chunks of elements from iterable source. * * Chunk size must be at least 1. * * @param chunkSize * * @see single.chunkwiseAsync */ chunkwise(chunkSize) { this.data = chunkwiseAsync(this.data, chunkSize); return this; } /** * Compress an iterable source by filtering out data that is not selected. * * Selectors indicate which data. True value selects item. False value filters out data. * * @param selectors * * @see single.compressAsync */ compress(selectors) { this.data = compressAsync(this.data, selectors); return this; } /** * Drop elements from the iterable source while the predicate function is true. * * Once the predicate function returns false once, all remaining elements are returned. * * @param predicate * * @see single.dropWhileAsync */ dropWhile(predicate) { this.data = dropWhileAsync(this.data, predicate); return this; } /** * Filter out elements from the iterable source only returning elements where there predicate function is true. * * @param predicate * * @see single.filterAsync */ filter(predicate) { this.data = filterAsync(this.data, predicate); return this; } /** * Enumerates items of given collection. * * @see single.enumerateAsync */ enumerate() { this.data = enumerateAsync(this.data); return this; } /** * Iterates keys from the collection of key-value pairs. * * @see single.keysAsync */ keys() { this.data = keysAsync(this.data); return this; } /** * Limit iteration to a max size limit. * * @param count * * @see single.limitAsync */ limit(count) { this.data = limitAsync(this.data, count); return this; } /** * Map a function onto every element of the stream * * @param mapper * * @see single.mapAsync */ map(mapper) { this.data = mapAsync(this.data, mapper); return this; } /** * Returns a new collection formed by applying a given callback function * to each element of the stream, and then flattening the result by one level. * * @param mapper * * @see single.flatMapAsync */ flatMap(mapper) { this.data = flatMapAsync(this.data, mapper); return this; } /** * Flatten a stream. * * @param dimensions * * @see single.flattenAsync */ flatten(dimensions = Infinity) { this.data = flattenAsync(this.data, dimensions); return this; } /** * Group stream data by a common data element. * * Iterate pairs of group name and collection of grouped items. * * Collection of grouped items may be an array or an object (depends on presence of `itemKeyFunction` param). * * The `groupKeyFunction` determines the key (or multiple keys) to group elements by. * * The `itemKeyFunction` (optional) determines the key of element in group. * * @param groupKeyFunction * @param itemKeyFunction * * @see single.groupByAsync */ groupBy(groupKeyFunction, itemKeyFunction) { this.data = groupByAsync(this.data, groupKeyFunction, itemKeyFunction); return this; } /** * Return pairs of elements from iterable source. * * Produces empty generator if given collection contains less than 2 elements. * * @see single.pairwiseAsync */ pairwise() { this.data = pairwiseAsync(this.data); return this; } /** * Accumulate the running average (mean) over the stream. * * @param initialValue (Optional) If provided, the running average leads off with the initial value. * * @see math.runningAverageAsync */ runningAverage(initialValue) { this.data = runningAverageAsync(this.data, initialValue); return this; } /** * Accumulate the running difference over the stream. * * @param initialValue (Optional) If provided, the running difference leads off with the initial value. * * @see math.runningDifferenceAsync */ runningDifference(initialValue) { this.data = runningDifferenceAsync(this.data, initialValue); return this; } /** * Accumulate the running max over the stream. * * @param initialValue (Optional) If provided, the running max leads off with the initial value. * * @see math.runningMaxAsync */ runningMax(initialValue) { this.data = runningMaxAsync(this.data, initialValue); return this; } /** * Accumulate the running min over the stream. * * @param initialValue (Optional) If provided, the running min leads off with the initial value. * * @see math.runningMinAsync */ runningMin(initialValue) { this.data = runningMinAsync(this.data, initialValue); return this; } /** * Accumulate the running product over the stream. * * @param initialValue (Optional) If provided, the running product leads off with the initial value. * * @see math.runningProductAsync */ runningProduct(initialValue) { this.data = runningProductAsync(this.data, initialValue); return this; } /** * Accumulate the running total over the stream. * * @param initialValue (Optional) If provided, the running total leads off with the initial value. * * @see math.runningTotalAsync */ runningTotal(initialValue) { this.data = runningTotalAsync(this.data, initialValue); return this; } /** * Skip n elements in the stream after optional offset. * * @param count * @param offset * * @see single.skipAsync */ skip(count, offset = 0) { this.data = skipAsync(this.data, count, offset); return this; } /** * Extract a slice of the stream. * * @param start * @param count * @param step * * @see single.sliceAsync */ slice(start = 0, count, step = 1) { this.data = sliceAsync(this.data, start, count, step); return this; } /** * Return elements from the iterable source as long as the predicate is true. * * If no predicate is provided, the boolean value of the data is used. * * @param predicate * * @see single.takeWhileAsync */ takeWhile(predicate) { this.data = takeWhileAsync(this.data, predicate); return this; } /** * Iterates values from the collection of key-value pairs. * * @see single.valuesAsync */ values() { this.data = valuesAsync(this.data); return this; } /** * Sorts the stream. * * If comparator is `undefined`, then elements of the iterable source must be comparable. * * @see single.sort */ sort(comparator) { this.data = sortAsync(this.data, comparator); return this; } /** * Filter out elements from the iterable source only returning unique elements. * * @param compareBy * * @see set.distinctAsync */ distinct(compareBy) { this.data = distinctAsync(this.data, compareBy); return this; } /** * Iterates the intersection of iterable source and given iterables. * * Always treats different instances of objects and arrays as unequal. * * @param iterables * * @see set.intersectionAsync */ intersectionWith(...iterables) { this.data = intersectionAsync(this.data, ...iterables); return this; } /** * Iterates partial intersection of iterable source and given iterables. * * Always treats different instances of objects and arrays as unequal. * * @param minIntersectionCount * @param iterables * * @see set.partialIntersectionAsync */ partialIntersectionWith(minIntersectionCount, ...iterables) { this.data = partialIntersectionAsync(minIntersectionCount, this.data, ...iterables); return this; } /** * Iterates the symmetric difference of iterable source and given iterables. * * Always treats different instances of objects and arrays as unequal. * * @param iterables * * @see set.symmetricDifferenceAsync */ symmetricDifferenceWith(...iterables) { this.data = symmetricDifferenceAsync(this.data, ...iterables); return this; } /** * Iterates union of iterable source and given iterables. * * Always treats different instances of objects and arrays as unequal. * * @param iterables * * @see set.unionAsync */ unionWith(...iterables) { this.data = unionAsync(this.data, ...iterables); return this; } /** * Iterates cartesian product of iterable source and given iterables. * * @param iterables * * @see combinatorics.cartesianProductAsync */ cartesianProductWith(...iterables) { this.data = cartesianProductAsync(this.data, ...iterables); return this; } /** * Iterates all permutations of iterable source. * * @param length * * @see combinatorics.permutations */ permutations(length) { this.data = permutationsAsync(this.data, length); return this; } /** * Iterates all combinations of iterable source. * * @param length * * @see combinatorics.combinations */ combinations(length) { this.data = combinationsAsync(this.data, length); return this; } /** * Peek at each element between other Stream operations to do some action without modifying the stream. * * Useful for debugging purposes. * * @param callback */ peek(callback) { const [data, peekable] = teeAsync(this.data, 2); this.data = data; (() => __awaiter(this, void 0, void 0, function* () { var _a, e_1, _b, _c; try { for (var _d = true, peekable_1 = __asyncValues(peekable), peekable_1_1; peekable_1_1 = yield peekable_1.next(), _a = peekable_1_1.done, !_a; _d = true) { _c = peekable_1_1.value; _d = false; const element = _c; callback(element); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = peekable_1.return)) yield _b.call(peekable_1); } finally { if (e_1) throw e_1.error; } } }))(); return this; } /** * Peek at the entire stream between other Stream operations to do some action without modifying the stream. * * Useful for debugging purposes. * * @param callback */ peekStream(callback) { const [data, peekable] = teeAsync(this.data, 2); this.data = data; callback(AsyncStream.of(peekable)); return this; } /** * Reduces iterable source like `array.reduce()` function. * * @param reducer * @param initialValue * * @see reduce.toValueAsync */ toValue(reducer, initialValue) { return __awaiter(this, void 0, void 0, function* () { return yield toValueAsync(this, reducer, initialValue); }); } /** * Reduces iterable source to the mean average of its items. * * Returns `undefined` if iterable source is empty. * * @see reduce.toAverageAsync */ toAverage() { return __awaiter(this, void 0, void 0, function* () { return yield toAverageAsync(this); }); } /** * Reduces iterable source to its length. * * @see reduce.toCountAsync */ toCount() { return __awaiter(this, void 0, void 0, function* () { return yield toCountAsync(this); }); } /** * Reduces iterable source to its max value. * * Callable param `compareBy` must return comparable value. * * If `compareBy` is not proposed then items of iterable source must be comparable. * * Returns `undefined` if iterable source is empty. * * @param compareBy * * @see reduce.toMaxAsync */ toMax(compareBy) { return __awaiter(this, void 0, void 0, function* () { return yield toMaxAsync(this, compareBy); }); } /** * Reduces iterable source to its min value. * * Callable param `compareBy` must return comparable value. * * If `compareBy` is not proposed then items of iterable source must be comparable. * * Returns `undefined` if iterable source is empty. * * @param compareBy * * @see reduce.toMinAsync */ toMin(compareBy) { return __awaiter(this, void 0, void 0, function* () { return yield toMinAsync(this, compareBy); }); } /** * Reduces given collection to array of its upper and lower bounds. * * Callable param `compareBy` must return comparable value. * * If `compareBy` is not proposed then items of given collection must be comparable. * * Returns `[undefined, undefined]` if given collection is empty. * * @param compareBy * * @see reduce.toMinMaxAsync */ toMinMax(compareBy) { return __awaiter(this, void 0, void 0, function* () { return yield toMinMaxAsync(this, compareBy); }); } /** * Returns the first element of stream. * * @throws LengthError if stream is empty. * * @see reduce.toFirstAsync */ toFirst() { return __awaiter(this, void 0, void 0, function* () { return yield toFirstAsync(this); }); } /** * Returns the first and last elements of stream. * * @throws LengthError if stream is empty. * * @see reduce.toFirstAndLastAsync */ toFirstAndLast() { return __awaiter(this, void 0, void 0, function* () { return yield toFirstAndLastAsync(this); }); } /** * Returns the first element of stream. * * @throws LengthError if stream is empty. * * @see reduce.toLastAsync */ toLast() { return __awaiter(this, void 0, void 0, function* () { return yield toLastAsync(this); }); } /** * Reduces iterable source to the sum of its items. * * @see reduce.toSumAsync */ toSum() { return __awaiter(this, void 0, void 0, function* () { return yield toSumAsync(this); }); } /** * Reduces iterable source to the product of its items. * * Returns `undefined` if iterable source is empty. * * @see reduce.toProductAsync */ toProduct() { return __awaiter(this, void 0, void 0, function* () { return yield toProductAsync(this); }); } /** * Reduces given collection to its range. * * Returns 0 if given collection is empty. * * @see reduce.toRangeAsync */ toRange() { return __awaiter(this, void 0, void 0, function* () { return yield toRangeAsync(this); }); } /** * Returns true if all elements of stream match the predicate function. * * For empty stream returns true. * * @param predicate * * @see summary.allMatchAsync */ allMatch(predicate) { return __awaiter(this, void 0, void 0, function* () { return yield allMatchAsync(this, predicate); }); } /** * Returns true if all elements of stream are unique. * * For empty stream returns true. * * Considers different instances of data containers to be different, even if they have the same content. * * @see summary.allUniqueAsync */ allUnique() { return __awaiter(this, void 0, void 0, function* () { return yield allUniqueAsync(this); }); } /** * Returns true if any element of stream matches the predicate function. * * For empty stream returns false. * * @param predicate * * @see summary.anyMatchAsync */ anyMatch(predicate) { return __awaiter(this, void 0, void 0, function* () { return yield anyMatchAsync(this, predicate); }); } /** * Returns true if exactly n items in the async iterable are true where the predicate function is true. * * Default predicate if not provided is the boolean value of each data item. * * @param n * @param predicate * * @see summary.exactlyNAsync */ exactlyN(n, predicate) { return __awaiter(this, void 0, void 0, function* () { return exactlyNAsync(this, n, predicate); }); } /** * Returns true if stream is sorted in ascending order; otherwise false. * * Items of stream source must be comparable. * * Also returns true if stream is empty or has only one element. * * @see summary.isSortedAsync */ isSorted() { return __awaiter(this, void 0, void 0, function* () { return yield isSortedAsync(this); }); } /** * Returns true if stream is sorted in descending order; otherwise false. * * Items of stream source must be comparable. * * Also returns true if stream is empty or has only one element. * * @see summary.isReversedAsync */ isReversed() { return __awaiter(this, void 0, void 0, function* () { return yield isReversedAsync(this); }); } /** * Returns true if no element of stream matches the predicate function. * * For empty stream returns true. * * @param predicate * * @see summary.noneMatchAsync */ noneMatch(predicate) { return __awaiter(this, void 0, void 0, function* () { return yield noneMatchAsync(this, predicate); }); } /** * Returns true if stream collection and all given collections are the same. * * For empty collections list returns true. * * @param collections * * @see summary.sameAsync */ sameWith(...collections) { return __awaiter(this, void 0, void 0, function* () { return yield sameAsync(this.data, ...collections); }); } /** * Returns true if stream collection and all given collections have the same lengths. * * For empty collections list returns true. * * @param collections * * @see summary.sameCountAsync */ sameCountWith(...collections) { return __awaiter(this, void 0, void 0, function* () { return yield sameCountAsync(this.data, ...collections); }); } /** * Return several independent async streams from current stream. * * Once a tee() has been created, the original iterable should not be used anywhere else; * otherwise, the iterable could get advanced without the tee objects being informed. * * This tool may require significant auxiliary storage (depending on how much temporary data needs to be stored). * In general, if one iterator uses most or all of the data before another iterator starts, * it is faster to use toArray() instead of tee(). * * @param count * * @see transform.teeAsync */ tee(count) { return teeAsync(this.data, count).map((iterable) => new AsyncStream(iterable)); } /** * Converts stream to Array. * * @see transform.toArrayAsync */ toArray() { return __awaiter(this, void 0, void 0, function* () { return yield toArrayAsync(this); }); } /** * Converts stream to Map. * * Stream collection must contain only key-value pairs as elements. * * @see transform.toMapAsync */ toMap() { return __awaiter(this, void 0, void 0, function* () { return yield toMapAsync(this); }); } /** * Converts stream to Set. * * @see transform.toSetAsync */ toSet() { return __awaiter(this, void 0, void 0, function* () { return yield toSetAsync(this); }); } /** * Aggregated iterator. */ [Symbol.asyncIterator]() { return __asyncGenerator(this, arguments, function* _a() { var _b, e_2, _c, _d; try { for (var _e = true, _f = __asyncValues(this.data), _g; _g = yield __await(_f.next()), _b = _g.done, !_b; _e = true) { _d = _g.value; _e = false; const datum = _d; yield yield __await(datum); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_e && !_b && (_c = _f.return)) yield __await(_c.call(_f)); } finally { if (e_2) throw e_2.error; } } }); } /** * Stream constructor. * * @param iterable */ constructor(iterable) { this.data = iterable; } } //# sourceMappingURL=async-stream.js.map