Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/workbench/contrib/notebook/common/notebookRange.ts
3296 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
* [start, end]
8
*/
9
export interface ICellRange {
10
/**
11
* zero based index
12
*/
13
start: number;
14
15
/**
16
* zero based index
17
*/
18
end: number;
19
}
20
21
22
export function isICellRange(candidate: any): candidate is ICellRange {
23
if (!candidate || typeof candidate !== 'object') {
24
return false;
25
}
26
return typeof (<ICellRange>candidate).start === 'number'
27
&& typeof (<ICellRange>candidate).end === 'number';
28
}
29
30
export function cellIndexesToRanges(indexes: number[]) {
31
indexes.sort((a, b) => a - b);
32
const first = indexes.shift();
33
34
if (first === undefined) {
35
return [];
36
}
37
38
return indexes.reduce(function (ranges, num) {
39
if (num <= ranges[0][1]) {
40
ranges[0][1] = num + 1;
41
} else {
42
ranges.unshift([num, num + 1]);
43
}
44
return ranges;
45
}, [[first, first + 1]]).reverse().map(val => ({ start: val[0], end: val[1] }));
46
}
47
48
export function cellRangesToIndexes(ranges: ICellRange[]) {
49
const indexes = ranges.reduce((a, b) => {
50
for (let i = b.start; i < b.end; i++) {
51
a.push(i);
52
}
53
54
return a;
55
}, [] as number[]);
56
57
return indexes;
58
}
59
60
export function reduceCellRanges(ranges: ICellRange[]): ICellRange[] {
61
const sorted = ranges.sort((a, b) => a.start - b.start);
62
const first = sorted[0];
63
64
if (!first) {
65
return [];
66
}
67
68
const reduced = sorted.reduce((prev: ICellRange[], curr) => {
69
const last = prev[prev.length - 1];
70
if (last.end >= curr.start) {
71
last.end = Math.max(last.end, curr.end);
72
} else {
73
prev.push(curr);
74
}
75
return prev;
76
}, [first] as ICellRange[]);
77
78
if (reduced.length > 1) {
79
// remove the (0, 0) range
80
return reduced.filter(range => !(range.start === range.end && range.start === 0));
81
}
82
83
return reduced;
84
}
85
86
export function cellRangesEqual(a: ICellRange[], b: ICellRange[]) {
87
a = reduceCellRanges(a);
88
b = reduceCellRanges(b);
89
if (a.length !== b.length) {
90
return false;
91
}
92
93
for (let i = 0; i < a.length; i++) {
94
if (a[i].start !== b[i].start || a[i].end !== b[i].end) {
95
return false;
96
}
97
}
98
99
return true;
100
}
101
102
/**
103
* todo@rebornix test and sort
104
* @param range
105
* @param other
106
* @returns
107
*/
108
109
export function cellRangeContains(range: ICellRange, other: ICellRange): boolean {
110
return other.start >= range.start && other.end <= range.end;
111
}
112
113