1 | import { flatten } from '../../utils/array'
|
2 | import { factory } from '../../utils/factory'
|
3 | import { improveErrorMessage } from './utils/improveErrorMessage'
|
4 |
|
5 | const name = 'mad'
|
6 | const dependencies = ['typed', 'abs', 'map', 'median', 'subtract']
|
7 |
|
8 | export const createMad = factory(name, dependencies, ({ typed, abs, map, median, subtract }) => {
|
9 | |
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | return typed(name, {
|
34 |
|
35 | 'Array | Matrix': _mad,
|
36 |
|
37 |
|
38 | '...': function (args) {
|
39 | return _mad(args)
|
40 | }
|
41 | })
|
42 |
|
43 | function _mad (array) {
|
44 | array = flatten(array.valueOf())
|
45 |
|
46 | if (array.length === 0) {
|
47 | throw new Error('Cannot calculate median absolute deviation (mad) of an empty array')
|
48 | }
|
49 |
|
50 | try {
|
51 | const med = median(array)
|
52 | return median(map(array, function (value) {
|
53 | return abs(subtract(value, med))
|
54 | }))
|
55 | } catch (err) {
|
56 | if (err instanceof TypeError && err.message.indexOf('median') !== -1) {
|
57 | throw new TypeError(err.message.replace('median', 'mad'))
|
58 | } else {
|
59 | throw improveErrorMessage(err, 'mad')
|
60 | }
|
61 | }
|
62 | }
|
63 | })
|