From d173542e2694d25b00583ff809f670319d8a88fd Mon Sep 17 00:00:00 2001 From: Luc Patiny Date: Thu, 28 Jul 2022 10:15:39 +0200 Subject: [PATCH] feat: add xMaxAbsoluteValue --- src/index.ts | 1 + src/x/__tests__/xMaxAbsoluteValue.test.ts | 21 +++++++++++++++ src/x/xMaxAbsoluteValue.ts | 32 +++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 src/x/__tests__/xMaxAbsoluteValue.test.ts create mode 100644 src/x/xMaxAbsoluteValue.ts diff --git a/src/index.ts b/src/index.ts index 7f2cad32..ff7b525e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,6 +26,7 @@ export * from './x/xIsMonotone'; export * from './x/xIsMonotoneIncreasing'; export * from './x/xMaxIndex'; export * from './x/xMaxValue'; +export * from './x/xMaxAbsoluteValue'; export * from './x/xMean'; export * from './x/xMeanAbsoluteError'; export * from './x/xMeanSquaredError'; diff --git a/src/x/__tests__/xMaxAbsoluteValue.test.ts b/src/x/__tests__/xMaxAbsoluteValue.test.ts new file mode 100644 index 00000000..e16653a4 --- /dev/null +++ b/src/x/__tests__/xMaxAbsoluteValue.test.ts @@ -0,0 +1,21 @@ +import { xMaxAbsoluteValue } from '../xMaxAbsoluteValue'; + +test('xMaxAbsoluteValue', () => { + let typedArray = new Int16Array(3); + typedArray[0] = 1; + typedArray[1] = 2; + typedArray[2] = -3; + + expect(xMaxAbsoluteValue([0])).toBe(0); + expect(xMaxAbsoluteValue([1])).toBe(1); + expect(xMaxAbsoluteValue([1, 2])).toBe(2); + expect(xMaxAbsoluteValue([1, 2, 1])).toBe(2); + expect(xMaxAbsoluteValue([3, 2, 1])).toBe(3); + expect(xMaxAbsoluteValue(typedArray)).toBe(3); + expect(xMaxAbsoluteValue([1, 2, 3], { fromIndex: 1 })).toBe(3); + expect(xMaxAbsoluteValue([3, 2, 1], { fromIndex: 1 })).toBe(2); + expect(xMaxAbsoluteValue([1, 2, 3], { toIndex: 1 })).toBe(2); + expect(xMaxAbsoluteValue([3, 2, 1], { toIndex: 1 })).toBe(3); + expect(xMaxAbsoluteValue([1, 2, 3], { fromIndex: 1, toIndex: 1 })).toBe(2); + expect(xMaxAbsoluteValue([3, 2, 1], { fromIndex: 1, toIndex: 1 })).toBe(2); +}); diff --git a/src/x/xMaxAbsoluteValue.ts b/src/x/xMaxAbsoluteValue.ts new file mode 100644 index 00000000..8b1c0cea --- /dev/null +++ b/src/x/xMaxAbsoluteValue.ts @@ -0,0 +1,32 @@ +import { NumberArray } from 'cheminfo-types'; + +import { xCheck } from './xCheck'; +import { xGetFromToIndex, XGetFromToIndexOptions } from './xGetFromToIndex'; + +/** + * Computes the maximal value of an array of values + * + * @param array - array of numbers + * @param options - options + */ +export function xMaxAbsoluteValue( + array: NumberArray, + options: XGetFromToIndexOptions = {}, +): number { + xCheck(array); + const { fromIndex, toIndex } = xGetFromToIndex(array, options); + let maxValue = array[fromIndex]; + + for (let i = fromIndex + 1; i <= toIndex; i++) { + if (array[i] >= 0) { + if (array[i] > maxValue) { + maxValue = array[i]; + } + } else { + if (-array[i] > maxValue) { + maxValue = -array[i]; + } + } + } + return maxValue; +}