Skip to content

Commit

Permalink
Add math.Round polyfill for pre1.10 (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
tyler-sommer committed Oct 8, 2020
1 parent 0570e5b commit 0361500
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 7 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Expand Up @@ -8,6 +8,7 @@ go:
- '1.11'
- '1.12'
- '1.13'
- '1.14'
- 'tip'

os:
Expand Down
9 changes: 5 additions & 4 deletions twig/filter/filter.go
Expand Up @@ -2,16 +2,17 @@
package filter // import "github.com/tyler-sommer/stick/twig/filter"

import (
"encoding/json"
"encoding/json"
"fmt"
"math"
"sort"
"strings"
"unicode/utf8"

"github.com/tyler-sommer/stick"
"reflect"
"time"

"github.com/tyler-sommer/stick"
)

// builtInFilters returns a map containing all built-in Twig filters,
Expand Down Expand Up @@ -417,7 +418,7 @@ func filterRound(ctx stick.Context, val stick.Value, args ...stick.Value) stick.
precision := 0
algo := ""
if len(args) > 0 {
precision = int(math.Round(stick.CoerceNumber(args[0])))
precision = int(mathRound(stick.CoerceNumber(args[0])))
}
if precision < 0 {
precision = 0
Expand All @@ -433,7 +434,7 @@ func filterRound(ctx stick.Context, val stick.Value, args ...stick.Value) stick.
case "floor":
return math.Floor(input*mult) / mult
default:
return math.Round(input*mult) / mult
return mathRound(input*mult) / mult
}
}

Expand Down
7 changes: 4 additions & 3 deletions twig/filter/filter_test.go
Expand Up @@ -3,9 +3,10 @@ package filter
import (
"testing"

"github.com/tyler-sommer/stick"
"strings"
"time"

"github.com/tyler-sommer/stick"
)

func TestFilters(t *testing.T) {
Expand Down Expand Up @@ -93,8 +94,8 @@ func TestFilters(t *testing.T) {
return filterReplace(nil, "I like %this% and %that%.", map[string]string{"%this%": "foo", "%that%": "bar"})
},
"I like foo and bar.",
},
{
},
{
"json encode",
func() stick.Value {
return filterJSONEncode(nil, map[string]interface{}{"a": 1, "b": true, "c": 3.14, "d": "a string", "e": []string{"one", "two"}, "f": map[string]interface{}{"alpha": "foo", "beta": nil}})
Expand Down
11 changes: 11 additions & 0 deletions twig/filter/round_go1.10.go
@@ -0,0 +1,11 @@
// +build go1.10

package filter

import (
"math"
)

func mathRound(f float64) float64 {
return math.Round(f)
}
15 changes: 15 additions & 0 deletions twig/filter/round_pre1.10.go
@@ -0,0 +1,15 @@
// +build !go1.10

package filter

import (
"math"
)

func mathRound(x float64) float64 {
t := math.Trunc(x)
if math.Abs(x-t) >= 0.5 {
return t + math.Copysign(1, x)
}
return t
}

0 comments on commit 0361500

Please sign in to comment.