File: numfns.go

package info (click to toggle)
golang-github-christrenkamp-goxpath 1.0~alpha3%2Bgit20170922.c385f95-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster
  • size: 308 kB
  • sloc: sh: 16; makefile: 3; xml: 3
file content (71 lines) | stat: -rw-r--r-- 1,428 bytes parent folder | download | duplicates (2)
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
}