Browse Source

SortedArray: add .isRange, improve .areEqual

Alexander Rose 3 years ago
parent
commit
c0144d826c

+ 1 - 1
src/mol-data/int/impl/ordered-set.ts

@@ -19,7 +19,7 @@ export const ofBounds = I.ofBounds;
 export function ofSortedArray(xs: Nums): OrderedSetImpl {
     if (!xs.length) return Empty;
     // check if the array is just a range
-    if (xs[xs.length - 1] - xs[0] + 1 === xs.length) return I.ofRange(xs[0], xs[xs.length - 1]);
+    if (S.isRange(xs)) return I.ofRange(xs[0], xs[xs.length - 1]);
     return xs as any;
 }
 

+ 3 - 1
src/mol-data/int/impl/sorted-array.ts

@@ -22,6 +22,7 @@ export function ofRange(min: number, max: number) {
     return ret;
 }
 export function is(xs: any): xs is Nums { return xs && (Array.isArray(xs) || !!xs.buffer); }
+export function isRange(xs: Nums) { return xs[xs.length - 1] - xs[0] + 1 === xs.length; }
 
 export function start(xs: Nums) { return xs[0]; }
 export function end(xs: Nums) { return xs[xs.length - 1] + 1;  }
@@ -61,6 +62,7 @@ export function areEqual(a: Nums, b: Nums) {
     if (a === b) return true;
     const aSize = a.length;
     if (aSize !== b.length || a[0] !== b[0] || a[aSize - 1] !== b[aSize - 1]) return false;
+    if (isRange(a)) return true;
     for (let i = 0; i < aSize; i++) {
         if (a[i] !== b[i]) return false;
     }
@@ -340,7 +342,7 @@ export function deduplicate(xs: Nums) {
 }
 
 export function indicesOf(a: Nums, b: Nums): Nums {
-    if (a === b) return ofSortedArray(createRangeArray(0, a.length - 1));
+    if (areEqual(a, b)) return ofSortedArray(createRangeArray(0, a.length - 1));
 
     const { startI: sI, startJ: sJ, endI, endJ } = getSuitableIntersectionRange(a, b);
     let i = sI, j = sJ;

+ 1 - 0
src/mol-data/int/sorted-array.ts

@@ -17,6 +17,7 @@ namespace SortedArray {
     /** create sorted array [min, max) (it does NOT contain the max value) */
     export const ofBounds: <T extends number = number>(min: T, max: T) => SortedArray<T> = (min, max) => Impl.ofRange(min, max - 1) as any;
     export const is: <T extends number = number>(v: any) => v is SortedArray<T> = Impl.is as any;
+    export const isRange: <T extends number = number>(array: ArrayLike<number>) => boolean = Impl.isRange as any;
 
     export const has: <T extends number = number>(array: SortedArray<T>, x: T) => boolean = Impl.has as any;
     /** Returns the index of `x` in `set` or -1 if not found. */