Skip to content

Commit bd46796

Browse files
authored
feat: add xAbsoluteSum method (#245)
1 parent 31c5fdb commit bd46796

File tree

4 files changed

+46
-0
lines changed

4 files changed

+46
-0
lines changed

src/__tests__/__snapshots__/index.test.ts.snap

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ exports[`test existence of exported functions 1`] = `
99
"getOutputArray",
1010
"xAbsolute",
1111
"xAbsoluteMedian",
12+
"xAbsoluteSum",
1213
"xAdd",
1314
"xApplyFunctionStr",
1415
"xAutoCorrelation",
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { expect, test } from 'vitest';
2+
3+
import { xAbsoluteSum } from '../index';
4+
5+
test('normal array', () => {
6+
const array = [-1, 2, -3, 4];
7+
expect(xAbsoluteSum(array)).toStrictEqual(10);
8+
});
9+
10+
test('typed array', () => {
11+
const array = new Float64Array([-1, 2, -3, 4]);
12+
expect(xAbsoluteSum(array)).toBe(10);
13+
});
14+
15+
test('typed array from to', () => {
16+
const array = new Float64Array([10, -1, 2, -3, 4, 20]);
17+
18+
const fromIndex = 1;
19+
const toIndex = 4;
20+
expect(xAbsoluteSum(array, { fromIndex, toIndex })).toBe(10);
21+
});

src/x/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
export * from './getOutputArray';
22
export * from './xAbsolute';
33
export * from './xAbsoluteMedian';
4+
export * from './xAbsoluteSum';
45
export * from './xAdd';
56
export * from './xApplyFunctionStr';
67
export * from './xAutoCorrelation';

src/x/xAbsoluteSum.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { NumberArray } from 'cheminfo-types';
2+
3+
import { xCheck } from './xCheck';
4+
import { XGetFromToIndexOptions, xGetFromToIndex } from './xGetFromToIndex';
5+
6+
export function xAbsoluteSum(
7+
array: NumberArray,
8+
options: XGetFromToIndexOptions = {},
9+
): number {
10+
xCheck(array);
11+
const { fromIndex, toIndex } = xGetFromToIndex(array, options);
12+
13+
let sum = 0;
14+
for (let i = fromIndex; i <= toIndex; i++) {
15+
if (array[i] < 0) {
16+
sum -= array[i];
17+
} else {
18+
sum += array[i];
19+
}
20+
}
21+
22+
return sum;
23+
}

0 commit comments

Comments
 (0)