-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathxPadding.ts
More file actions
81 lines (72 loc) · 1.98 KB
/
xPadding.ts
File metadata and controls
81 lines (72 loc) · 1.98 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { NumberArray } from 'cheminfo-types';
import { xCheck } from './xCheck.ts';
import { xEnsureFloat64 } from './xEnsureFloat64.ts';
export interface XPaddingOptions {
/**
* padding size before first element and after last element
* @default 0
*/
size?: number;
/**
* value to use for padding (if algorithm='value')
* @default 0
*/
value?: number;
/**
* Padding strategy: `value` fills with a constant, `duplicate` repeats the first/last element, `circular` wraps the array.
* @default undefined
*/
algorithm?: 'value' | 'duplicate' | 'circular';
}
/**
* Pads an array symmetrically on both sides.
* @param array - the array that will be padded
* @param options - options
* @returns padded Float64Array
*/
export function xPadding(
array: NumberArray,
options: XPaddingOptions = {},
): Float64Array<ArrayBuffer> {
const { size = 0, value = 0, algorithm } = options;
xCheck(array);
if (!algorithm) {
return xEnsureFloat64(array);
}
const result = new Float64Array(array.length + size * 2);
for (let i = 0; i < array.length; i++) {
result[i + size] = array[i];
}
const fromEnd = size + array.length;
const toEnd = 2 * size + array.length;
switch (algorithm) {
case 'value':
for (let i = 0; i < size; i++) {
result[i] = value;
}
for (let i = fromEnd; i < toEnd; i++) {
result[i] = value;
}
break;
case 'duplicate':
for (let i = 0; i < size; i++) {
result[i] = array[0];
}
for (let i = fromEnd; i < toEnd; i++) {
result[i] = array.at(-1) as number;
}
break;
case 'circular':
for (let i = 0; i < size; i++) {
result[i] =
array[(array.length - (size % array.length) + i) % array.length];
}
for (let i = 0; i < size; i++) {
result[i + fromEnd] = array[i % array.length];
}
break;
default:
throw new Error(`unknown algorithm ${String(algorithm)}`);
}
return result;
}