Skip to content

Commit

Permalink
feat: add builtin function: type
Browse files Browse the repository at this point in the history
  • Loading branch information
chyroc committed Jan 28, 2019
1 parent 93917a4 commit d413d2f
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 0 deletions.
11 changes: 11 additions & 0 deletions docs/builtins.md
Expand Up @@ -91,6 +91,17 @@ Tries to convert an object to string object. See [this](https://github.com/d5/te
x := string(123) // v == "123"
```

## type_name

Returns the type_name of an object.

```golang
type_name(1) // int
type_name("str") // string
type_name([1, 2, 3]) // array
```


Optionally it can take the second argument, which will be returned if the first argument cannot be converted to string. Note that the second argument does not have to be string.

```golang
Expand Down
9 changes: 9 additions & 0 deletions objects/builtin_type.go
@@ -0,0 +1,9 @@
package objects

func builtinTypeName(args ...Object) (Object, error) {
if len(args) != 1 {
return nil, ErrWrongNumArguments
}

return &String{Value: args[0].TypeName()}, nil
}
4 changes: 4 additions & 0 deletions objects/builtins.go
Expand Up @@ -96,4 +96,8 @@ var Builtins = []NamedBuiltinFunc{
Name: "from_json",
Func: builtinFromJSON,
},
{
Name: "type_name",
Func: builtinTypeName,
},
}
13 changes: 13 additions & 0 deletions runtime/vm_builtin_test.go
Expand Up @@ -149,4 +149,17 @@ func TestBuiltinFunction(t *testing.T) {
expect(t, `out = sprintf("foo %v %d", [1, "bar", true], 19)`, "foo [1 bar true] 19")
expectError(t, `sprintf(1)`) // format has to be String
expectError(t, `sprintf('c')`) // format has to be String

// type_name
expect(t, `out = type_name(1)`, "int")
expect(t, `out = type_name(1.1)`, "float")
expect(t, `out = type_name("a")`, "string")
expect(t, `out = type_name([1,2,3])`, "array")
expect(t, `out = type_name({k:1})`, "map")
expect(t, `out = type_name('a')`, "char")
expect(t, `out = type_name(true)`, "bool")
expect(t, `out = type_name(false)`, "bool")
expect(t, `out = type_name(bytes( 1))`, "bytes")
expect(t, `out = type_name(undefined)`, "undefined")
expect(t, `out = type_name(error("err"))`, "error")
}

0 comments on commit d413d2f

Please sign in to comment.