1 | import { containsCollections, deepForEach, reduce } from '../../utils/collection'
|
2 | import { factory } from '../../utils/factory'
|
3 | import { improveErrorMessage } from './utils/improveErrorMessage'
|
4 | import { noBignumber, noFraction } from '../../utils/noop'
|
5 |
|
6 | const name = 'sum'
|
7 | const dependencies = ['typed', 'config', 'add', '?bignumber', '?fraction']
|
8 |
|
9 | export const createSum = factory(name, dependencies, ({ typed, config, add, bignumber, fraction }) => {
|
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': _sum,
|
36 |
|
37 |
|
38 | 'Array | Matrix, number | BigNumber': _nsumDim,
|
39 |
|
40 |
|
41 | '...': function (args) {
|
42 | if (containsCollections(args)) {
|
43 | throw new TypeError('Scalar values expected in function sum')
|
44 | }
|
45 |
|
46 | return _sum(args)
|
47 | }
|
48 | })
|
49 |
|
50 | |
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | function _sum (array) {
|
57 | let sum
|
58 |
|
59 | deepForEach(array, function (value) {
|
60 | try {
|
61 | sum = (sum === undefined) ? value : add(sum, value)
|
62 | } catch (err) {
|
63 | throw improveErrorMessage(err, 'sum', value)
|
64 | }
|
65 | })
|
66 |
|
67 | if (sum === undefined) {
|
68 | switch (config.number) {
|
69 | case 'number':
|
70 | return 0
|
71 | case 'BigNumber':
|
72 | return bignumber ? bignumber(0) : noBignumber()
|
73 | case 'Fraction':
|
74 | return fraction ? fraction(0) : noFraction()
|
75 | default:
|
76 | return 0
|
77 | }
|
78 | }
|
79 |
|
80 | return sum
|
81 | }
|
82 |
|
83 | function _nsumDim (array, dim) {
|
84 | try {
|
85 | const sum = reduce(array, dim, add)
|
86 | return sum
|
87 | } catch (err) {
|
88 | throw improveErrorMessage(err, 'sum')
|
89 | }
|
90 | }
|
91 | })
|