diff --git a/eval/builtin_func.go b/eval/builtin_func.go index 6509a816..36997920 100644 --- a/eval/builtin_func.go +++ b/eval/builtin_func.go @@ -67,6 +67,7 @@ func init() { &BuiltinFn{"take", wrapFn(take)}, &BuiltinFn{"drop", wrapFn(drop)}, + &BuiltinFn{"len", wrapFn(lenFn)}, &BuiltinFn{"count", wrapFn(count)}, &BuiltinFn{"-sleep", wrapFn(_sleep)}, @@ -508,6 +509,23 @@ func drop(ec *EvalCtx, n int) { } } +func lenFn(ec *EvalCtx, v Value) { + var l int + switch v := v.(type) { + case String: + l = len(v) + case List: + l = len(*v.inner) + case Map: + l = len(*v.inner) + case *Struct: + l = len(v.FieldNames) + default: + throw(fmt.Errorf("cannot get length of a %s", v.Kind())) + } + ec.ports[1].Chan <- String(strconv.Itoa(l)) +} + func count(ec *EvalCtx) { in := ec.ports[0].Chan out := ec.ports[1].Chan