This repository has been archived by the owner on Apr 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
numfns.go
71 lines (55 loc) · 1.39 KB
/
numfns.go
1
2
3
4
5
6
7
8
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package intfns
import (
"fmt"
"math"
"github.com/ChrisTrenkamp/goxpath/tree"
)
func number(c tree.Ctx, args ...tree.Result) (tree.Result, error) {
if b, ok := args[0].(tree.IsNum); ok {
return b.Num(), nil
}
return nil, fmt.Errorf("Cannot convert object to a number")
}
func sum(c tree.Ctx, args ...tree.Result) (tree.Result, error) {
n, ok := args[0].(tree.NodeSet)
if !ok {
return nil, fmt.Errorf("Cannot convert object to a node-set")
}
ret := 0.0
for _, i := range n {
ret += float64(tree.GetNodeNum(i))
}
return tree.Num(ret), nil
}
func floor(c tree.Ctx, args ...tree.Result) (tree.Result, error) {
n, ok := args[0].(tree.IsNum)
if !ok {
return nil, fmt.Errorf("Cannot convert object to a number")
}
return tree.Num(math.Floor(float64(n.Num()))), nil
}
func ceiling(c tree.Ctx, args ...tree.Result) (tree.Result, error) {
n, ok := args[0].(tree.IsNum)
if !ok {
return nil, fmt.Errorf("Cannot convert object to a number")
}
return tree.Num(math.Ceil(float64(n.Num()))), nil
}
func round(c tree.Ctx, args ...tree.Result) (tree.Result, error) {
isn, ok := args[0].(tree.IsNum)
if !ok {
return nil, fmt.Errorf("Cannot convert object to a number")
}
n := isn.Num()
if math.IsNaN(float64(n)) || math.IsInf(float64(n), 0) {
return n, nil
}
if n < -0.5 {
n = tree.Num(int(n - 0.5))
} else if n > 0.5 {
n = tree.Num(int(n + 0.5))
} else {
n = 0
}
return n, nil
}