Skip to content

Commit 55d4764

Browse files
authored
vam: round() (#5598)
1 parent 967e0f8 commit 55d4764

File tree

4 files changed

+51
-0
lines changed

4 files changed

+51
-0
lines changed

runtime/sam/expr/function/math.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,9 +139,14 @@ type Round struct {
139139
func (r *Round) Call(_ super.Allocator, args []super.Value) super.Value {
140140
val := args[0]
141141
switch id := val.Type().ID(); {
142+
case id == super.IDNull:
143+
return val
142144
case super.IsUnsigned(id) || super.IsSigned(id):
143145
return val
144146
case super.IsFloat(id):
147+
if val.IsNull() {
148+
return val
149+
}
145150
return super.NewFloat(val.Type(), math.Round(val.Float()))
146151
}
147152
return r.zctx.WrapError("round: not a number", val)

runtime/vam/expr/function/function.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ func New(zctx *super.Context, name string, narg int) (expr.Function, field.Path,
6565
case "replace":
6666
argmin, argmax = 3, 3
6767
f = &Replace{zctx}
68+
case "round":
69+
f = &Round{zctx}
6870
case "rune_len":
6971
f = &RuneLen{zctx}
7072
case "split":

runtime/vam/expr/function/math.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,29 @@ func (l *Log) Call(args ...vector.Any) vector.Any {
179179
return out
180180
}
181181

182+
// https://github.com/brimdata/super/blob/main/docs/language/functions.md#round
183+
type Round struct {
184+
zctx *super.Context
185+
}
186+
187+
func (r *Round) Call(args ...vector.Any) vector.Any {
188+
vec := args[0]
189+
switch id := vec.Type().ID(); {
190+
case id == super.IDNull:
191+
return vec
192+
case super.IsUnsigned(id) || super.IsSigned(id):
193+
return vec
194+
case super.IsFloat(id):
195+
vals := make([]float64, vec.Len())
196+
for i := range vec.Len() {
197+
v, _ := vector.FloatValue(vec, i)
198+
vals[i] = math.Round(v)
199+
}
200+
return vector.NewFloat(vec.Type(), vals, vector.NullsOf(vec))
201+
}
202+
return vector.NewWrappedError(r.zctx, "round: not a number", vec)
203+
}
204+
182205
// https://github.com/brimdata/super/blob/main/docs/language/functions.md#sqrt
183206
type Sqrt struct {
184207
zctx *super.Context
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
zed: "round(this)"
2+
3+
vector: true
4+
5+
input: |
6+
-1
7+
2(uint64)
8+
1.5
9+
2.4
10+
null(float64)
11+
null
12+
"foo"
13+
14+
output: |
15+
-1
16+
2(uint64)
17+
2.
18+
2.
19+
null(float64)
20+
null
21+
error({message:"round: not a number",on:"foo"})

0 commit comments

Comments
 (0)