cef15f52a07045294f65d17fdccab44b85ae6f58
1 import { isEmptyArray
} from
'./Utils.js'
4 * Computes the average of the given data set.
6 * @param dataSet - Data set.
7 * @returns The average of the given data set.
10 export const average
= (dataSet
: number[]): number => {
11 if (Array.isArray(dataSet
) && dataSet
.length
=== 0) {
14 if (Array.isArray(dataSet
) && dataSet
.length
=== 1) {
17 return dataSet
.reduce((accumulator
, nb
) => accumulator
+ nb
, 0) / dataSet
.length
21 * Computes the median of the given data set.
23 * @param dataSet - Data set.
24 * @returns The median of the given data set.
27 export const median
= (dataSet
: number[]): number => {
28 if (isEmptyArray(dataSet
)) {
31 if (Array.isArray(dataSet
) && dataSet
.length
=== 1) {
34 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
)
36 (sortedDataSet
[(sortedDataSet
.length
- 1) >> 1] + sortedDataSet
[sortedDataSet
.length
>> 1]) / 2
40 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
41 export const nthPercentile
= (dataSet
: number[], percentile
: number): number => {
42 if (percentile
< 0 && percentile
> 100) {
43 throw new RangeError('Percentile is not between 0 and 100')
45 if (isEmptyArray(dataSet
)) {
48 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
)
49 if (percentile
=== 0 || sortedDataSet
.length
=== 1) {
50 return sortedDataSet
[0]
52 if (percentile
=== 100) {
53 return sortedDataSet
[sortedDataSet
.length
- 1]
55 const percentileIndexBase
= (percentile
/ 100) * (sortedDataSet
.length
- 1)
56 const percentileIndexInteger
= Math.floor(percentileIndexBase
)
57 if (sortedDataSet
[percentileIndexInteger
+ 1] != null) {
59 sortedDataSet
[percentileIndexInteger
] +
60 (percentileIndexBase
- percentileIndexInteger
) *
61 (sortedDataSet
[percentileIndexInteger
+ 1] - sortedDataSet
[percentileIndexInteger
])
64 return sortedDataSet
[percentileIndexInteger
]
68 * Computes the sample standard deviation of the given data set.
70 * @param dataSet - Data set.
71 * @param dataSetAverage - Average of the data set.
72 * @returns The sample standard deviation of the given data set.
73 * @see https://en.wikipedia.org/wiki/Unbiased_estimation_of_standard_deviation
76 export const stdDeviation
= (
78 dataSetAverage
: number = average(dataSet
)
80 if (isEmptyArray(dataSet
)) {
83 if (Array.isArray(dataSet
) && dataSet
.length
=== 1) {
87 dataSet
.reduce((accumulator
, num
) => accumulator
+ Math.pow(num
- dataSetAverage
, 2), 0) /