diff --git a/common/changes/@visactor/vutils/fix-maxInArray_2024-11-28-06-57.json b/common/changes/@visactor/vutils/fix-maxInArray_2024-11-28-06-57.json new file mode 100644 index 0000000..5a13022 --- /dev/null +++ b/common/changes/@visactor/vutils/fix-maxInArray_2024-11-28-06-57.json @@ -0,0 +1,10 @@ +{ + "changes": [ + { + "packageName": "@visactor/vutils", + "comment": "fix: fix incorrect results in `maxInArray` and `minInArray` with custom comparison functions.", + "type": "none" + } + ], + "packageName": "@visactor/vutils" +} \ No newline at end of file diff --git a/packages/vutils/__tests__/common/array.test.ts b/packages/vutils/__tests__/common/array.test.ts index 25b4056..7780609 100644 --- a/packages/vutils/__tests__/common/array.test.ts +++ b/packages/vutils/__tests__/common/array.test.ts @@ -1,4 +1,4 @@ -import { shuffleArray } from '../../src'; +import { minInArray, maxInArray, shuffleArray } from '../../src'; const values = [1, 2, 3, 4, 5, 6]; @@ -11,3 +11,13 @@ describe('shuffleArray', () => { expect(values.every(v => result.includes(v))).toBeTruthy(); }); }); + +describe('maxInArray and minInArray', () => { + it('maxInArray/minInArray with custom compare function', () => { + const list = [{ value: 1 }, { value: 3 }, { value: 2 }]; + const max = maxInArray(list, (a, b) => a.value - b.value); + const min = minInArray(list, (a, b) => a.value - b.value); + expect(max).toEqual(list[1]); + expect(min).toEqual(list[0]); + }); +}); diff --git a/packages/vutils/src/common/array.ts b/packages/vutils/src/common/array.ts index 3d4c416..569de1f 100644 --- a/packages/vutils/src/common/array.ts +++ b/packages/vutils/src/common/array.ts @@ -52,7 +52,7 @@ export const maxInArray = (arr: T[], compareFn?: (a: T, b: T) => number): T | let max = arr[0]; for (let i = 1; i < arr.length; i++) { const value = arr[i]; - if (compareFn?.(value, max) ?? (value as number) - (max as number) > 0) { + if ((compareFn?.(value, max) ?? (value as number) - (max as number)) > 0) { max = value; } } @@ -72,7 +72,7 @@ export const minInArray = (arr: T[], compareFn?: (a: T, b: T) => number): T | let min = arr[0]; for (let i = 1; i < arr.length; i++) { const value = arr[i]; - if (compareFn?.(value, min) ?? (value as number) - (min as number) < 0) { + if ((compareFn?.(value, min) ?? (value as number) - (min as number)) < 0) { min = value; } }