Debian Codegraph @

node/@xterm/xterm/src/vs/base/common/arrays.ts

raw
1 /*---------------------------------------------------------------------------------------------
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT License. See License.txt in the project root for license information.
4 *--------------------------------------------------------------------------------------------*/
5
6 import { CancellationToken } from 'vs/base/common/cancellation';
7 import { CancellationError } from 'vs/base/common/errors';
8 import { ISplice } from 'vs/base/common/sequence';
9 import { findFirstIdxMonotonousOrArrLen } from './arraysFind';
10
11 /**
12 * Returns the last element of an array.
13 * @param array The array.
14 * @param n Which element from the end (default is zero).
15 */
16 export function tail<T>(array: ArrayLike<T>, n: number = 0): T | undefined {
17 return array[array.length - (1 + n)];
18 }
19
20 export function tail2<T>(arr: T[]): [T[], T] {
21 if (arr.length === 0) {
22 throw new Error('Invalid tail call');
23 }
24
25 return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
26 }
27
28 export function equals<T>(one: ReadonlyArray<T> | undefined, other: ReadonlyArray<T> | undefined, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b): boolean {
29 if (one === other) {
30 return true;
31 }
32
33 if (!one || !other) {
34 return false;
35 }
36
37 if (one.length !== other.length) {
38 return false;
39 }
40
41 for (let i = 0, len = one.length; i < len; i++) {
42 if (!itemEquals(one[i], other[i])) {
43 return false;
44 }
45 }
46
47 return true;
48 }
49
50 /**
51 * Remove the element at `index` by replacing it with the last element. This is faster than `splice`
52 * but changes the order of the array
53 */
54 export function removeFastWithoutKeepingOrder<T>(array: T[], index: number) {
55 const last = array.length - 1;
56 if (index < last) {
57 array[index] = array[last];
58 }
59 array.pop();
60 }
61
62 /**
63 * Performs a binary search algorithm over a sorted array.
64 *
65 * @param array The array being searched.
66 * @param key The value we search for.
67 * @param comparator A function that takes two array elements and returns zero
68 * if they are equal, a negative number if the first element precedes the
69 * second one in the sorting order, or a positive number if the second element
70 * precedes the first one.
71 * @return See {@link binarySearch2}
72 */
73 export function binarySearch<T>(array: ReadonlyArray<T>, key: T, comparator: (op1: T, op2: T) => number): number {
74 return binarySearch2(array.length, i => comparator(array[i], key));
75 }
76
77 /**
78 * Performs a binary search algorithm over a sorted collection. Useful for cases
79 * when we need to perform a binary search over something that isn't actually an
80 * array, and converting data to an array would defeat the use of binary search
81 * in the first place.
82 *
83 * @param length The collection length.
84 * @param compareToKey A function that takes an index of an element in the
85 * collection and returns zero if the value at this index is equal to the
86 * search key, a negative number if the value precedes the search key in the
87 * sorting order, or a positive number if the search key precedes the value.
88 * @return A non-negative index of an element, if found. If not found, the
89 * result is -(n+1) (or ~n, using bitwise notation), where n is the index
90 * where the key should be inserted to maintain the sorting order.
91 */
92 export function binarySearch2(length: number, compareToKey: (index: number) => number): number {
93 let low = 0,
94 high = length - 1;
95
96 while (low <= high) {
97 const mid = ((low + high) / 2) | 0;
98 const comp = compareToKey(mid);
99 if (comp < 0) {
100 low = mid + 1;
101 } else if (comp > 0) {
102 high = mid - 1;
103 } else {
104 return mid;
105 }
106 }
107 return -(low + 1);
108 }
109
110 type Compare<T> = (a: T, b: T) => number;
111
112
113 export function quickSelect<T>(nth: number, data: T[], compare: Compare<T>): T {
114
115 nth = nth | 0;
116
117 if (nth >= data.length) {
118 throw new TypeError('invalid index');
119 }
120
121 const pivotValue = data[Math.floor(data.length * Math.random())];
122 const lower: T[] = [];
123 const higher: T[] = [];
124 const pivots: T[] = [];
125
126 for (const value of data) {
127 const val = compare(value, pivotValue);
128 if (val < 0) {
129 lower.push(value);
130 } else if (val > 0) {
131 higher.push(value);
132 } else {
133 pivots.push(value);
134 }
135 }
136
137 if (nth < lower.length) {
138 return quickSelect(nth, lower, compare);
139 } else if (nth < lower.length + pivots.length) {
140 return pivots[0];
141 } else {
142 return quickSelect(nth - (lower.length + pivots.length), higher, compare);
143 }
144 }
145
146 export function groupBy<T>(data: ReadonlyArray<T>, compare: (a: T, b: T) => number): T[][] {
147 const result: T[][] = [];
148 let currentGroup: T[] | undefined = undefined;
149 for (const element of data.slice(0).sort(compare)) {
150 if (!currentGroup || compare(currentGroup[0], element) !== 0) {
151 currentGroup = [element];
152 result.push(currentGroup);
153 } else {
154 currentGroup.push(element);
155 }
156 }
157 return result;
158 }
159
160 /**
161 * Splits the given items into a list of (non-empty) groups.
162 * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group.
163 * The order of the items is preserved.
164 */
165 export function* groupAdjacentBy<T>(items: Iterable<T>, shouldBeGrouped: (item1: T, item2: T) => boolean): Iterable<T[]> {
166 let currentGroup: T[] | undefined;
167 let last: T | undefined;
168 for (const item of items) {
169 if (last !== undefined && shouldBeGrouped(last, item)) {
170 currentGroup!.push(item);
171 } else {
172 if (currentGroup) {
173 yield currentGroup;
174 }
175 currentGroup = [item];
176 }
177 last = item;
178 }
179 if (currentGroup) {
180 yield currentGroup;
181 }
182 }
183
184 export function forEachAdjacent<T>(arr: T[], f: (item1: T | undefined, item2: T | undefined) => void): void {
185 for (let i = 0; i <= arr.length; i++) {
186 f(i === 0 ? undefined : arr[i - 1], i === arr.length ? undefined : arr[i]);
187 }
188 }
189
190 export function forEachWithNeighbors<T>(arr: T[], f: (before: T | undefined, element: T, after: T | undefined) => void): void {
191 for (let i = 0; i < arr.length; i++) {
192 f(i === 0 ? undefined : arr[i - 1], arr[i], i + 1 === arr.length ? undefined : arr[i + 1]);
193 }
194 }
195
196 interface IMutableSplice<T> extends ISplice<T> {
197 readonly toInsert: T[];
198 deleteCount: number;
199 }
200
201 /**
202 * Diffs two *sorted* arrays and computes the splices which apply the diff.
203 */
204 export function sortedDiff<T>(before: ReadonlyArray<T>, after: ReadonlyArray<T>, compare: (a: T, b: T) => number): ISplice<T>[] {
205 const result: IMutableSplice<T>[] = [];
206
207 function pushSplice(start: number, deleteCount: number, toInsert: T[]): void {
208 if (deleteCount === 0 && toInsert.length === 0) {
209 return;
210 }
211
212 const latest = result[result.length - 1];
213
214 if (latest && latest.start + latest.deleteCount === start) {
215 latest.deleteCount += deleteCount;
216 latest.toInsert.push(...toInsert);
217 } else {
218 result.push({ start, deleteCount, toInsert });
219 }
220 }
221
222 let beforeIdx = 0;
223 let afterIdx = 0;
224
225 while (true) {
226 if (beforeIdx === before.length) {
227 pushSplice(beforeIdx, 0, after.slice(afterIdx));
228 break;
229 }
230 if (afterIdx === after.length) {
231 pushSplice(beforeIdx, before.length - beforeIdx, []);
232 break;
233 }
234
235 const beforeElement = before[beforeIdx];
236 const afterElement = after[afterIdx];
237 const n = compare(beforeElement, afterElement);
238 if (n === 0) {
239 // equal
240 beforeIdx += 1;
241 afterIdx += 1;
242 } else if (n < 0) {
243 // beforeElement is smaller -> before element removed
244 pushSplice(beforeIdx, 1, []);
245 beforeIdx += 1;
246 } else if (n > 0) {
247 // beforeElement is greater -> after element added
248 pushSplice(beforeIdx, 0, [afterElement]);
249 afterIdx += 1;
250 }
251 }
252
253 return result;
254 }
255
256 /**
257 * Takes two *sorted* arrays and computes their delta (removed, added elements).
258 * Finishes in `Math.min(before.length, after.length)` steps.
259 */
260 export function delta<T>(before: ReadonlyArray<T>, after: ReadonlyArray<T>, compare: (a: T, b: T) => number): { removed: T[]; added: T[] } {
261 const splices = sortedDiff(before, after, compare);
262 const removed: T[] = [];
263 const added: T[] = [];
264
265 for (const splice of splices) {
266 removed.push(...before.slice(splice.start, splice.start + splice.deleteCount));
267 added.push(...splice.toInsert);
268 }
269
270 return { removed, added };
271 }
272
273 /**
274 * Returns the top N elements from the array.
275 *
276 * Faster than sorting the entire array when the array is a lot larger than N.
277 *
278 * @param array The unsorted array.
279 * @param compare A sort function for the elements.
280 * @param n The number of elements to return.
281 * @return The first n elements from array when sorted with compare.
282 */
283 export function top<T>(array: ReadonlyArray<T>, compare: (a: T, b: T) => number, n: number): T[] {
284 if (n === 0) {
285 return [];
286 }
287 const result = array.slice(0, n).sort(compare);
288 topStep(array, compare, result, n, array.length);
289 return result;
290 }
291
292 /**
293 * Asynchronous variant of `top()` allowing for splitting up work in batches between which the event loop can run.
294 *
295 * Returns the top N elements from the array.
296 *
297 * Faster than sorting the entire array when the array is a lot larger than N.
298 *
299 * @param array The unsorted array.
300 * @param compare A sort function for the elements.
301 * @param n The number of elements to return.
302 * @param batch The number of elements to examine before yielding to the event loop.
303 * @return The first n elements from array when sorted with compare.
304 */
305 export function topAsync<T>(array: T[], compare: (a: T, b: T) => number, n: number, batch: number, token?: CancellationToken): Promise<T[]> {
306 if (n === 0) {
307 return Promise.resolve([]);
308 }
309
310 return new Promise((resolve, reject) => {
311 (async () => {
312 const o = array.length;
313 const result = array.slice(0, n).sort(compare);
314 for (let i = n, m = Math.min(n + batch, o); i < o; i = m, m = Math.min(m + batch, o)) {
315 if (i > n) {
316 await new Promise(resolve => setTimeout(resolve)); // any other delay function would starve I/O
317 }
318 if (token && token.isCancellationRequested) {
319 throw new CancellationError();
320 }
321 topStep(array, compare, result, i, m);
322 }
323 return result;
324 })()
325 .then(resolve, reject);
326 });
327 }
328
329 function topStep<T>(array: ReadonlyArray<T>, compare: (a: T, b: T) => number, result: T[], i: number, m: number): void {
330 for (const n = result.length; i < m; i++) {
331 const element = array[i];
332 if (compare(element, result[n - 1]) < 0) {
333 result.pop();
334 const j = findFirstIdxMonotonousOrArrLen(result, e => compare(element, e) < 0);
335 result.splice(j, 0, element);
336 }
337 }
338 }
339
340 /**
341 * @returns New array with all falsy values removed. The original array IS NOT modified.
342 */
343 export function coalesce<T>(array: ReadonlyArray<T | undefined | null>): T[] {
344 return array.filter((e): e is T => !!e);
345 }
346
347 /**
348 * Remove all falsy values from `array`. The original array IS modified.
349 */
350 export function coalesceInPlace<T>(array: Array<T | undefined | null>): asserts array is Array<T> {
351 let to = 0;
352 for (let i = 0; i < array.length; i++) {
353 if (!!array[i]) {
354 array[to] = array[i];
355 to += 1;
356 }
357 }
358 array.length = to;
359 }
360
361 /**
362 * @deprecated Use `Array.copyWithin` instead
363 */
364 export function move(array: any[], from: number, to: number): void {
365 array.splice(to, 0, array.splice(from, 1)[0]);
366 }
367
368 /**
369 * @returns false if the provided object is an array and not empty.
370 */
371 export function isFalsyOrEmpty(obj: any): boolean {
372 return !Array.isArray(obj) || obj.length === 0;
373 }
374
375 /**
376 * @returns True if the provided object is an array and has at least one element.
377 */
378 export function isNonEmptyArray<T>(obj: T[] | undefined | null): obj is T[];
379 export function isNonEmptyArray<T>(obj: readonly T[] | undefined | null): obj is readonly T[];
380 export function isNonEmptyArray<T>(obj: T[] | readonly T[] | undefined | null): obj is T[] | readonly T[] {
381 return Array.isArray(obj) && obj.length > 0;
382 }
383
384 /**
385 * Removes duplicates from the given array. The optional keyFn allows to specify
386 * how elements are checked for equality by returning an alternate value for each.
387 */
388 export function distinct<T>(array: ReadonlyArray<T>, keyFn: (value: T) => any = value => value): T[] {
389 const seen = new Set<any>();
390
391 return array.filter(element => {
392 const key = keyFn!(element);
393 if (seen.has(key)) {
394 return false;
395 }
396 seen.add(key);
397 return true;
398 });
399 }
400
401 export function uniqueFilter<T, R>(keyFn: (t: T) => R): (t: T) => boolean {
402 const seen = new Set<R>();
403
404 return element => {
405 const key = keyFn(element);
406
407 if (seen.has(key)) {
408 return false;
409 }
410
411 seen.add(key);
412 return true;
413 };
414 }
415
416 export function firstOrDefault<T, NotFound = T>(array: ReadonlyArray<T>, notFoundValue: NotFound): T | NotFound;
417 export function firstOrDefault<T>(array: ReadonlyArray<T>): T | undefined;
418 export function firstOrDefault<T, NotFound = T>(array: ReadonlyArray<T>, notFoundValue?: NotFound): T | NotFound | undefined {
419 return array.length > 0 ? array[0] : notFoundValue;
420 }
421
422 export function lastOrDefault<T, NotFound = T>(array: ReadonlyArray<T>, notFoundValue: NotFound): T | NotFound;
423 export function lastOrDefault<T>(array: ReadonlyArray<T>): T | undefined;
424 export function lastOrDefault<T, NotFound = T>(array: ReadonlyArray<T>, notFoundValue?: NotFound): T | NotFound | undefined {
425 return array.length > 0 ? array[array.length - 1] : notFoundValue;
426 }
427
428 export function commonPrefixLength<T>(one: ReadonlyArray<T>, other: ReadonlyArray<T>, equals: (a: T, b: T) => boolean = (a, b) => a === b): number {
429 let result = 0;
430
431 for (let i = 0, len = Math.min(one.length, other.length); i < len && equals(one[i], other[i]); i++) {
432 result++;
433 }
434
435 return result;
436 }
437
438 export function range(to: number): number[];
439 export function range(from: number, to: number): number[];
440 export function range(arg: number, to?: number): number[] {
441 let from = typeof to === 'number' ? arg : 0;
442
443 if (typeof to === 'number') {
444 from = arg;
445 } else {
446 from = 0;
447 to = arg;
448 }
449
450 const result: number[] = [];
451
452 if (from <= to) {
453 for (let i = from; i < to; i++) {
454 result.push(i);
455 }
456 } else {
457 for (let i = from; i > to; i--) {
458 result.push(i);
459 }
460 }
461
462 return result;
463 }
464
465 export function index<T>(array: ReadonlyArray<T>, indexer: (t: T) => string): { [key: string]: T };
466 export function index<T, R>(array: ReadonlyArray<T>, indexer: (t: T) => string, mapper: (t: T) => R): { [key: string]: R };
467 export function index<T, R>(array: ReadonlyArray<T>, indexer: (t: T) => string, mapper?: (t: T) => R): { [key: string]: R } {
468 return array.reduce((r, t) => {
469 r[indexer(t)] = mapper ? mapper(t) : t;
470 return r;
471 }, Object.create(null));
472 }
473
474 /**
475 * Inserts an element into an array. Returns a function which, when
476 * called, will remove that element from the array.
477 *
478 * @deprecated In almost all cases, use a `Set<T>` instead.
479 */
480 export function insert<T>(array: T[], element: T): () => void {
481 array.push(element);
482
483 return () => remove(array, element);
484 }
485
486 /**
487 * Removes an element from an array if it can be found.
488 *
489 * @deprecated In almost all cases, use a `Set<T>` instead.
490 */
491 export function remove<T>(array: T[], element: T): T | undefined {
492 const index = array.indexOf(element);
493 if (index > -1) {
494 array.splice(index, 1);
495
496 return element;
497 }
498
499 return undefined;
500 }
501
502 /**
503 * Insert `insertArr` inside `target` at `insertIndex`.
504 * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array
505 */
506 export function arrayInsert<T>(target: T[], insertIndex: number, insertArr: T[]): T[] {
507 const before = target.slice(0, insertIndex);
508 const after = target.slice(insertIndex);
509 return before.concat(insertArr, after);
510 }
511
512 /**
513 * Uses Fisher-Yates shuffle to shuffle the given array
514 */
515 export function shuffle<T>(array: T[], _seed?: number): void {
516 let rand: () => number;
517
518 if (typeof _seed === 'number') {
519 let seed = _seed;
520 // Seeded random number generator in JS. Modified from:
521 // https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript
522 rand = () => {
523 const x = Math.sin(seed++) * 179426549; // throw away most significant digits and reduce any potential bias
524 return x - Math.floor(x);
525 };
526 } else {
527 rand = Math.random;
528 }
529
530 for (let i = array.length - 1; i > 0; i -= 1) {
531 const j = Math.floor(rand() * (i + 1));
532 const temp = array[i];
533 array[i] = array[j];
534 array[j] = temp;
535 }
536 }
537
538 /**
539 * Pushes an element to the start of the array, if found.
540 */
541 export function pushToStart<T>(arr: T[], value: T): void {
542 const index = arr.indexOf(value);
543
544 if (index > -1) {
545 arr.splice(index, 1);
546 arr.unshift(value);
547 }
548 }
549
550 /**
551 * Pushes an element to the end of the array, if found.
552 */
553 export function pushToEnd<T>(arr: T[], value: T): void {
554 const index = arr.indexOf(value);
555
556 if (index > -1) {
557 arr.splice(index, 1);
558 arr.push(value);
559 }
560 }
561
562 export function pushMany<T>(arr: T[], items: ReadonlyArray<T>): void {
563 for (const item of items) {
564 arr.push(item);
565 }
566 }
567
568 export function mapArrayOrNot<T, U>(items: T | T[], fn: (_: T) => U): U | U[] {
569 return Array.isArray(items) ?
570 items.map(fn) :
571 fn(items);
572 }
573
574 export function asArray<T>(x: T | T[]): T[];
575 export function asArray<T>(x: T | readonly T[]): readonly T[];
576 export function asArray<T>(x: T | T[]): T[] {
577 return Array.isArray(x) ? x : [x];
578 }
579
580 export function getRandomElement<T>(arr: T[]): T | undefined {
581 return arr[Math.floor(Math.random() * arr.length)];
582 }
583
584 /**
585 * Insert the new items in the array.
586 * @param array The original array.
587 * @param start The zero-based location in the array from which to start inserting elements.
588 * @param newItems The items to be inserted
589 */
590 export function insertInto<T>(array: T[], start: number, newItems: T[]): void {
591 const startIdx = getActualStartIndex(array, start);
592 const originalLength = array.length;
593 const newItemsLength = newItems.length;
594 array.length = originalLength + newItemsLength;
595 // Move the items after the start index, start from the end so that we don't overwrite any value.
596 for (let i = originalLength - 1; i >= startIdx; i--) {
597 array[i + newItemsLength] = array[i];
598 }
599
600 for (let i = 0; i < newItemsLength; i++) {
601 array[i + startIdx] = newItems[i];
602 }
603 }
604
605 /**
606 * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it
607 * can only support limited number of items due to the maximum call stack size limit.
608 * @param array The original array.
609 * @param start The zero-based location in the array from which to start removing elements.
610 * @param deleteCount The number of elements to remove.
611 * @returns An array containing the elements that were deleted.
612 */
613 export function splice<T>(array: T[], start: number, deleteCount: number, newItems: T[]): T[] {
614 const index = getActualStartIndex(array, start);
615 let result = array.splice(index, deleteCount);
616 if (result === undefined) {
617 // see https://bugs.webkit.org/show_bug.cgi?id=261140
618 result = [];
619 }
620 insertInto(array, index, newItems);
621 return result;
622 }
623
624 /**
625 * Determine the actual start index (same logic as the native splice() or slice())
626 * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided.
627 * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0.
628 * @param array The target array.
629 * @param start The operation index.
630 */
631 function getActualStartIndex<T>(array: T[], start: number): number {
632 return start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length);
633 }
634
635 /**
636 * When comparing two values,
637 * a negative number indicates that the first value is less than the second,
638 * a positive number indicates that the first value is greater than the second,
639 * and zero indicates that neither is the case.
640 */
641 export type CompareResult = number;
642
643 export namespace CompareResult {
644 export function isLessThan(result: CompareResult): boolean {
645 return result < 0;
646 }
647
648 export function isLessThanOrEqual(result: CompareResult): boolean {
649 return result <= 0;
650 }
651
652 export function isGreaterThan(result: CompareResult): boolean {
653 return result > 0;
654 }
655
656 export function isNeitherLessOrGreaterThan(result: CompareResult): boolean {
657 return result === 0;
658 }
659
660 export const greaterThan = 1;
661 export const lessThan = -1;
662 export const neitherLessOrGreaterThan = 0;
663 }
664
665 /**
666 * A comparator `c` defines a total order `<=` on `T` as following:
667 * `c(a, b) <= 0` iff `a` <= `b`.
668 * We also have `c(a, b) == 0` iff `c(b, a) == 0`.
669 */
670 export type Comparator<T> = (a: T, b: T) => CompareResult;
671
672 export function compareBy<TItem, TCompareBy>(selector: (item: TItem) => TCompareBy, comparator: Comparator<TCompareBy>): Comparator<TItem> {
673 return (a, b) => comparator(selector(a), selector(b));
674 }
675
676 export function tieBreakComparators<TItem>(...comparators: Comparator<TItem>[]): Comparator<TItem> {
677 return (item1, item2) => {
678 for (const comparator of comparators) {
679 const result = comparator(item1, item2);
680 if (!CompareResult.isNeitherLessOrGreaterThan(result)) {
681 return result;
682 }
683 }
684 return CompareResult.neitherLessOrGreaterThan;
685 };
686 }
687
688 /**
689 * The natural order on numbers.
690 */
691 export const numberComparator: Comparator<number> = (a, b) => a - b;
692
693 export const booleanComparator: Comparator<boolean> = (a, b) => numberComparator(a ? 1 : 0, b ? 1 : 0);
694
695 export function reverseOrder<TItem>(comparator: Comparator<TItem>): Comparator<TItem> {
696 return (a, b) => -comparator(a, b);
697 }
698
699 export class ArrayQueue<T> {
700 private firstIdx = 0;
701 private lastIdx = this.items.length - 1;
702
703 /**
704 * Constructs a queue that is backed by the given array. Runtime is O(1).
705 */
706 constructor(private readonly items: readonly T[]) { }
707
708 get length(): number {
709 return this.lastIdx - this.firstIdx + 1;
710 }
711
712 /**
713 * Consumes elements from the beginning of the queue as long as the predicate returns true.
714 * If no elements were consumed, `null` is returned. Has a runtime of O(result.length).
715 */
716 takeWhile(predicate: (value: T) => boolean): T[] | null {
717 // P(k) := k <= this.lastIdx && predicate(this.items[k])
718 // Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s)
719
720 let startIdx = this.firstIdx;
721 while (startIdx < this.items.length && predicate(this.items[startIdx])) {
722 startIdx++;
723 }
724 const result = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx);
725 this.firstIdx = startIdx;
726 return result;
727 }
728
729 /**
730 * Consumes elements from the end of the queue as long as the predicate returns true.
731 * If no elements were consumed, `null` is returned.
732 * The result has the same order as the underlying array!
733 */
734 takeFromEndWhile(predicate: (value: T) => boolean): T[] | null {
735 // P(k) := this.firstIdx >= k && predicate(this.items[k])
736 // Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx]
737
738 let endIdx = this.lastIdx;
739 while (endIdx >= 0 && predicate(this.items[endIdx])) {
740 endIdx--;
741 }
742 const result = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1);
743 this.lastIdx = endIdx;
744 return result;
745 }
746
747 peek(): T | undefined {
748 if (this.length === 0) {
749 return undefined;
750 }
751 return this.items[this.firstIdx];
752 }
753
754 peekLast(): T | undefined {
755 if (this.length === 0) {
756 return undefined;
757 }
758 return this.items[this.lastIdx];
759 }
760
761 dequeue(): T | undefined {
762 const result = this.items[this.firstIdx];
763 this.firstIdx++;
764 return result;
765 }
766
767 removeLast(): T | undefined {
768 const result = this.items[this.lastIdx];
769 this.lastIdx--;
770 return result;
771 }
772
773 takeCount(count: number): T[] {
774 const result = this.items.slice(this.firstIdx, this.firstIdx + count);
775 this.firstIdx += count;
776 return result;
777 }
778 }
779
780 /**
781 * This class is faster than an iterator and array for lazy computed data.
782 */
783 export class CallbackIterable<T> {
784 public static readonly empty = new CallbackIterable<never>(_callback => { });
785
786 constructor(
787 /**
788 * Calls the callback for every item.
789 * Stops when the callback returns false.
790 */
791 public readonly iterate: (callback: (item: T) => boolean) => void
792 ) {
793 }
794
795 forEach(handler: (item: T) => void) {
796 this.iterate(item => { handler(item); return true; });
797 }
798
799 toArray(): T[] {
800 const result: T[] = [];
801 this.iterate(item => { result.push(item); return true; });
802 return result;
803 }
804
805 filter(predicate: (item: T) => boolean): CallbackIterable<T> {
806 return new CallbackIterable(cb => this.iterate(item => predicate(item) ? cb(item) : true));
807 }
808
809 map<TResult>(mapFn: (item: T) => TResult): CallbackIterable<TResult> {
810 return new CallbackIterable<TResult>(cb => this.iterate(item => cb(mapFn(item))));
811 }
812
813 some(predicate: (item: T) => boolean): boolean {
814 let result = false;
815 this.iterate(item => { result = predicate(item); return !result; });
816 return result;
817 }
818
819 findFirst(predicate: (item: T) => boolean): T | undefined {
820 let result: T | undefined;
821 this.iterate(item => {
822 if (predicate(item)) {
823 result = item;
824 return false;
825 }
826 return true;
827 });
828 return result;
829 }
830
831 findLast(predicate: (item: T) => boolean): T | undefined {
832 let result: T | undefined;
833 this.iterate(item => {
834 if (predicate(item)) {
835 result = item;
836 }
837 return true;
838 });
839 return result;
840 }
841
842 findLastMaxBy(comparator: Comparator<T>): T | undefined {
843 let result: T | undefined;
844 let first = true;
845 this.iterate(item => {
846 if (first || CompareResult.isGreaterThan(comparator(item, result!))) {
847 first = false;
848 result = item;
849 }
850 return true;
851 });
852 return result;
853 }
854 }
855
856 /**
857 * Represents a re-arrangement of items in an array.
858 */
859 export class Permutation {
860 constructor(private readonly _indexMap: readonly number[]) { }
861
862 /**
863 * Returns a permutation that sorts the given array according to the given compare function.
864 */
865 public static createSortPermutation<T>(arr: readonly T[], compareFn: (a: T, b: T) => number): Permutation {
866 const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2]));
867 return new Permutation(sortIndices);
868 }
869
870 /**
871 * Returns a new array with the elements of the given array re-arranged according to this permutation.
872 */
873 apply<T>(arr: readonly T[]): T[] {
874 return arr.map((_, index) => arr[this._indexMap[index]]);
875 }
876
877 /**
878 * Returns a new permutation that undoes the re-arrangement of this permutation.
879 */
880 inverse(): Permutation {
881 const inverseIndexMap = this._indexMap.slice();
882 for (let i = 0; i < this._indexMap.length; i++) {
883 inverseIndexMap[this._indexMap[i]] = i;
884 }
885 return new Permutation(inverseIndexMap);
886 }
887 }