Skip to content

Commit

Permalink
Merge pull request #215 from VisActor/fix/maxInArray
Browse files Browse the repository at this point in the history
fix: fix incorrect results in `maxInArray` and `minInArray` with cust…
  • Loading branch information
xile611 authored Nov 28, 2024
2 parents 82b84dc + 4480ae8 commit 49e7504
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -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"
}
12 changes: 11 additions & 1 deletion packages/vutils/__tests__/common/array.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { shuffleArray } from '../../src';
import { minInArray, maxInArray, shuffleArray } from '../../src';

const values = [1, 2, 3, 4, 5, 6];

Expand All @@ -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]);
});
});
4 changes: 2 additions & 2 deletions packages/vutils/src/common/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const maxInArray = <T>(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;
}
}
Expand All @@ -72,7 +72,7 @@ export const minInArray = <T>(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;
}
}
Expand Down

0 comments on commit 49e7504

Please sign in to comment.