Path: blob/main/extensions/copilot/src/util/common/arrays.ts
13397 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45/**6* Counts the number of elements in an array that satisfy a given predicate.7*/8export function count<T>(array: T[], predicate: (value: T) => boolean): number {9let count = 0;10for (const value of array) {11if (predicate(value)) {12count++;13}14}15return count;16}1718export function findInsertionIndexInSortedArray<T>(array: T[], value: T, isBeforeFunction: (a: T, b: T) => boolean): number {19let low = 0;20let high = array.length;21while (low < high) {22const mid = (low + high) >>> 1;23if (isBeforeFunction(array[mid], value)) {24low = mid + 1;25}26else {27high = mid;28}29}30return low;31}32/**33* Returns the maximum element in the array according to the given sort callback.34* @param arr - The array to search for the maximum element.35* @param compare - The sort callback to use for comparing elements.36* @returns The maximum element in the array according to the given sort callback.37*/38export function max<T>(arr: T[], compare: (a: T, b: T) => number): T | undefined {39if (arr.length === 0) {40return undefined;41}4243let maxElement = arr[0];4445for (let i = 1; i < arr.length; i++) {46const currentElement = arr[i];4748if (compare(currentElement, maxElement) > 0) {49maxElement = currentElement;50}51}5253return maxElement;54}5556export function filterMap<T, K>(array: T[], map: (t: T) => K | undefined | null): K[] {57const result: K[] = [];58for (const element of array) {59const mapped = map(element);60if (mapped !== undefined && mapped !== null) {61result.push(mapped);62}63}64return result;65}6667/**68* Behaves just like `Math.min`, so it will return Infinity for an empty array.69*/70export function min(array: number[]): number {71if (array.length === 0) {72return Infinity;73}7475let min = array[0];76for (let i = 1; i < array.length; i++) {77min = Math.min(min, array[i]);78}79return min;80}8182/**83*84* Last batch may not match batch size.85*/86export function* batchArrayElements<T>(array: T[], batchSize: number): Iterable<T[]> {87for (let i = 0; i < array.length; i += batchSize) {88yield array.slice(i, i + batchSize);89}90}919293