-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathxGetFromToIndex.ts
More file actions
64 lines (56 loc) · 1.56 KB
/
xGetFromToIndex.ts
File metadata and controls
64 lines (56 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import type { NumberArray } from 'cheminfo-types';
import { xFindClosestIndex } from './xFindClosestIndex.ts';
export interface XGetFromToIndexOptions {
/**
* Start index (0-based, clamped to array bounds). Takes precedence over `from`.
* @default 0
*/
fromIndex?: number;
/**
* End index (0-based, clamped to array bounds). Takes precedence over `to`.
* @default x.length-1
*/
toIndex?: number;
/**
* Start value in the x scale; resolved to the nearest index.
* @default x[0]
*/
from?: number;
/**
* End value in the x scale; resolved to the nearest index.
* @default x[x.length-1]
*/
to?: number;
}
/**
* Returns an object with {fromIndex, toIndex} for a specific from / to
* @param x - array of numbers
* @param options - Options
*/
export function xGetFromToIndex(
x: NumberArray,
options: XGetFromToIndexOptions = {},
): { fromIndex: number; toIndex: number } {
let { fromIndex, toIndex } = options;
const { from, to } = options;
if (fromIndex === undefined) {
if (from !== undefined) {
fromIndex = xFindClosestIndex(x, from);
} else {
fromIndex = 0;
}
}
if (toIndex === undefined) {
if (to !== undefined) {
toIndex = xFindClosestIndex(x, to);
} else {
toIndex = x.length - 1;
}
}
if (fromIndex < 0) fromIndex = 0;
if (toIndex < 0) toIndex = 0;
if (fromIndex >= x.length) fromIndex = x.length - 1;
if (toIndex >= x.length) toIndex = x.length - 1;
if (fromIndex > toIndex) [fromIndex, toIndex] = [toIndex, fromIndex];
return { fromIndex, toIndex };
}