Skip to content

Commit 08bab8a

Browse files
authored
feat: compact selection from array (#1067)
1 parent ac317c5 commit 08bab8a

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

packages/core/src/internal/data-grid/data-grid-types.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,13 @@ export class CompactSelection {
567567
return CompactSelection.empty().add(selection);
568568
};
569569

570+
static fromArray = (items: readonly number[]): CompactSelection => {
571+
if (items.length === 0) return CompactSelection.empty();
572+
const slices = items.map(s => [s, s + 1] as Slice);
573+
const newItems = mergeRanges(slices);
574+
return new CompactSelection(newItems);
575+
};
576+
570577
public offset(amount: number): CompactSelection {
571578
if (amount === 0) return this;
572579
const newItems = this.items.map(x => [x[0] + amount, x[1] + amount] as Slice);
@@ -575,9 +582,7 @@ export class CompactSelection {
575582

576583
public add(selection: number | Slice): CompactSelection {
577584
const slice: Slice = typeof selection === "number" ? [selection, selection + 1] : selection;
578-
579585
const newItems = mergeRanges([...this.items, slice]);
580-
581586
return new CompactSelection(newItems);
582587
}
583588

packages/core/test/data-grid-types.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,17 @@ describe("data-grid-types", () => {
7979
expect(sel.toArray()).toEqual([3, 4]);
8080
});
8181

82+
test("Compact selection fromArray", () => {
83+
const sel = CompactSelection.fromArray([3, 4, 6]);
84+
expect([...sel]).toEqual([3, 4, 6]);
85+
});
86+
87+
test("Compact selection array roundtrip", () => {
88+
const sel = CompactSelection.fromSingleSelection([2, 7]).add(8);
89+
const altSel = CompactSelection.fromArray(sel.toArray());
90+
expect(altSel.equals(sel)).toBe(true);
91+
});
92+
8293
test("Smoke test compact selection remove", () => {
8394
const sel = CompactSelection.fromSingleSelection([3, 8]);
8495

0 commit comments

Comments
 (0)