Path: blob/main/src/vs/workbench/contrib/notebook/common/notebookRange.ts
3296 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* [start, end]7*/8export interface ICellRange {9/**10* zero based index11*/12start: number;1314/**15* zero based index16*/17end: number;18}192021export function isICellRange(candidate: any): candidate is ICellRange {22if (!candidate || typeof candidate !== 'object') {23return false;24}25return typeof (<ICellRange>candidate).start === 'number'26&& typeof (<ICellRange>candidate).end === 'number';27}2829export function cellIndexesToRanges(indexes: number[]) {30indexes.sort((a, b) => a - b);31const first = indexes.shift();3233if (first === undefined) {34return [];35}3637return indexes.reduce(function (ranges, num) {38if (num <= ranges[0][1]) {39ranges[0][1] = num + 1;40} else {41ranges.unshift([num, num + 1]);42}43return ranges;44}, [[first, first + 1]]).reverse().map(val => ({ start: val[0], end: val[1] }));45}4647export function cellRangesToIndexes(ranges: ICellRange[]) {48const indexes = ranges.reduce((a, b) => {49for (let i = b.start; i < b.end; i++) {50a.push(i);51}5253return a;54}, [] as number[]);5556return indexes;57}5859export function reduceCellRanges(ranges: ICellRange[]): ICellRange[] {60const sorted = ranges.sort((a, b) => a.start - b.start);61const first = sorted[0];6263if (!first) {64return [];65}6667const reduced = sorted.reduce((prev: ICellRange[], curr) => {68const last = prev[prev.length - 1];69if (last.end >= curr.start) {70last.end = Math.max(last.end, curr.end);71} else {72prev.push(curr);73}74return prev;75}, [first] as ICellRange[]);7677if (reduced.length > 1) {78// remove the (0, 0) range79return reduced.filter(range => !(range.start === range.end && range.start === 0));80}8182return reduced;83}8485export function cellRangesEqual(a: ICellRange[], b: ICellRange[]) {86a = reduceCellRanges(a);87b = reduceCellRanges(b);88if (a.length !== b.length) {89return false;90}9192for (let i = 0; i < a.length; i++) {93if (a[i].start !== b[i].start || a[i].end !== b[i].end) {94return false;95}96}9798return true;99}100101/**102* todo@rebornix test and sort103* @param range104* @param other105* @returns106*/107108export function cellRangeContains(range: ICellRange, other: ICellRange): boolean {109return other.start >= range.start && other.end <= range.end;110}111112113