1 | import { factory } from '../../utils/factory'
|
2 | import { deepMap } from '../../utils/collection'
|
3 |
|
4 | const name = 'fix'
|
5 | const dependencies = ['typed', 'Complex', 'ceil', 'floor']
|
6 |
|
7 | export const createFix = /* #__PURE__ */ factory(name, dependencies, ({ typed, Complex, ceil, floor }) => {
|
8 | /**
|
9 | * Round a value towards zero.
|
10 | * For matrices, the function is evaluated element wise.
|
11 | *
|
12 | * Syntax:
|
13 | *
|
14 | * math.fix(x)
|
15 | *
|
16 | * Examples:
|
17 | *
|
18 | * math.fix(3.2) // returns number 3
|
19 | * math.fix(3.8) // returns number 3
|
20 | * math.fix(-4.2) // returns number -4
|
21 | * math.fix(-4.7) // returns number -4
|
22 | *
|
23 | * const c = math.complex(3.2, -2.7)
|
24 | * math.fix(c) // returns Complex 3 - 2i
|
25 | *
|
26 | * math.fix([3.2, 3.8, -4.7]) // returns Array [3, 3, -4]
|
27 | *
|
28 | * See also:
|
29 | *
|
30 | * ceil, floor, round
|
31 | *
|
32 | * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
|
33 | * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
|
34 | */
|
35 | const fix = typed('fix', {
|
36 | number: function (x) {
|
37 | return (x > 0) ? floor(x) : ceil(x)
|
38 | },
|
39 |
|
40 | Complex: function (x) {
|
41 | return new Complex(
|
42 | (x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
|
43 | (x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
|
44 | )
|
45 | },
|
46 |
|
47 | BigNumber: function (x) {
|
48 | return x.isNegative() ? ceil(x) : floor(x)
|
49 | },
|
50 |
|
51 | Fraction: function (x) {
|
52 | return x.s < 0 ? x.ceil() : x.floor()
|
53 | },
|
54 |
|
55 | 'Array | Matrix': function (x) {
|
56 | // deep map collection, skip zeros since fix(0) = 0
|
57 | return deepMap(x, fix, true)
|
58 | }
|
59 | })
|
60 |
|
61 | return fix
|
62 | })
|