Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/util/common/arrays.ts
13397 views
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
/**
7
* Counts the number of elements in an array that satisfy a given predicate.
8
*/
9
export function count<T>(array: T[], predicate: (value: T) => boolean): number {
10
let count = 0;
11
for (const value of array) {
12
if (predicate(value)) {
13
count++;
14
}
15
}
16
return count;
17
}
18
19
export function findInsertionIndexInSortedArray<T>(array: T[], value: T, isBeforeFunction: (a: T, b: T) => boolean): number {
20
let low = 0;
21
let high = array.length;
22
while (low < high) {
23
const mid = (low + high) >>> 1;
24
if (isBeforeFunction(array[mid], value)) {
25
low = mid + 1;
26
}
27
else {
28
high = mid;
29
}
30
}
31
return low;
32
}
33
/**
34
* Returns the maximum element in the array according to the given sort callback.
35
* @param arr - The array to search for the maximum element.
36
* @param compare - The sort callback to use for comparing elements.
37
* @returns The maximum element in the array according to the given sort callback.
38
*/
39
export function max<T>(arr: T[], compare: (a: T, b: T) => number): T | undefined {
40
if (arr.length === 0) {
41
return undefined;
42
}
43
44
let maxElement = arr[0];
45
46
for (let i = 1; i < arr.length; i++) {
47
const currentElement = arr[i];
48
49
if (compare(currentElement, maxElement) > 0) {
50
maxElement = currentElement;
51
}
52
}
53
54
return maxElement;
55
}
56
57
export function filterMap<T, K>(array: T[], map: (t: T) => K | undefined | null): K[] {
58
const result: K[] = [];
59
for (const element of array) {
60
const mapped = map(element);
61
if (mapped !== undefined && mapped !== null) {
62
result.push(mapped);
63
}
64
}
65
return result;
66
}
67
68
/**
69
* Behaves just like `Math.min`, so it will return Infinity for an empty array.
70
*/
71
export function min(array: number[]): number {
72
if (array.length === 0) {
73
return Infinity;
74
}
75
76
let min = array[0];
77
for (let i = 1; i < array.length; i++) {
78
min = Math.min(min, array[i]);
79
}
80
return min;
81
}
82
83
/**
84
*
85
* Last batch may not match batch size.
86
*/
87
export function* batchArrayElements<T>(array: T[], batchSize: number): Iterable<T[]> {
88
for (let i = 0; i < array.length; i += batchSize) {
89
yield array.slice(i, i + batchSize);
90
}
91
}
92
93