Skip to content

Commit 3402597

Browse files
authored
fix: median aggregation function (#4837)
1 parent ef5ae7d commit 3402597

File tree

2 files changed

+15
-11
lines changed

2 files changed

+15
-11
lines changed

packages/table-core/src/aggregationFns.ts

+11-11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { AggregationFn } from './features/Grouping'
2+
import { isNumberArray } from './utils'
23

34
const sum: AggregationFn<any> = (columnId, _leafRows, childRows) => {
45
// It's faster to just add the aggregations together instead of
@@ -82,18 +83,17 @@ const median: AggregationFn<any> = (columnId, leafRows) => {
8283
return
8384
}
8485

85-
let min = 0
86-
let max = 0
87-
88-
leafRows.forEach(row => {
89-
let value = row.getValue(columnId)
90-
if (typeof value === 'number') {
91-
min = Math.min(min, value)
92-
max = Math.max(max, value)
93-
}
94-
})
86+
const values = leafRows.map(row => row.getValue(columnId))
87+
if (!isNumberArray(values)) {
88+
return
89+
}
90+
if (values.length === 1) {
91+
return values[0]
92+
}
9593

96-
return (min + max) / 2
94+
const mid = Math.floor(values.length / 2)
95+
const nums = values.sort((a, b) => a - b)
96+
return values.length % 2 !== 0 ? nums[mid] : (nums[mid - 1]! + nums[mid]!) / 2
9797
}
9898

9999
const unique: AggregationFn<any> = (columnId, leafRows) => {

packages/table-core/src/utils.ts

+4
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,10 @@ export function isFunction<T extends AnyFunction>(d: any): d is T {
103103
return d instanceof Function
104104
}
105105

106+
export function isNumberArray(d: any): d is number[] {
107+
return Array.isArray(d) && d.every(val => typeof val === 'number')
108+
}
109+
106110
export function flattenBy<TNode>(
107111
arr: TNode[],
108112
getChildren: (item: TNode) => TNode[]

0 commit comments

Comments
 (0)