Merge pull request #55 from Chyroc/feat-builtin-function-type
feat: add builtin function: type
This commit is contained in:
commit
481d79cf68
4 changed files with 37 additions and 0 deletions
|
@ -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
|
||||
|
|
9
objects/builtin_type.go
Normal file
9
objects/builtin_type.go
Normal file
|
@ -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
|
||||
}
|
|
@ -96,4 +96,8 @@ var Builtins = []NamedBuiltinFunc{
|
|||
Name: "from_json",
|
||||
Func: builtinFromJSON,
|
||||
},
|
||||
{
|
||||
Name: "type_name",
|
||||
Func: builtinTypeName,
|
||||
},
|
||||
}
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue