-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathstring.go
95 lines (83 loc) · 1.86 KB
/
string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package gates
import (
"math"
"strconv"
"strings"
"unicode/utf8"
)
type String string
func (String) IsString() bool { return true }
func (String) IsInt() bool { return false }
func (String) IsFloat() bool { return false }
func (String) IsBool() bool { return false }
func (String) IsFunction() bool { return false }
func (s String) ToString() string { return string(s) }
func (s String) ToInt() int64 {
i, _ := strconv.ParseInt(string(s), 0, 64)
return i
}
func (s String) ToFloat() float64 {
f, err := strconv.ParseFloat(string(s), 64)
if err != nil {
return math.NaN()
}
return f
}
func (s String) ToNumber() Number {
t := strings.TrimSpace(string(s))
i, err := strconv.ParseInt(t, 0, 64)
if err == nil {
return Int(i)
}
return Float(s.ToFloat())
}
func (s String) ToBool() bool { return string(s) != "" }
func (s String) ToFunction() Function { return _EmptyFunction }
func (s String) ToNative(...ToNativeOption) interface{} { return string(s) }
func (s String) Equals(other Value) bool {
switch {
case other.IsString():
return s.SameAs(other)
case other.IsInt(), other.IsFloat(), other.IsBool():
return s.ToNumber().Equals(other)
default:
return false
}
}
func (s String) SameAs(b Value) bool {
bs, ok := b.(String)
if !ok {
return false
}
return string(bs) == string(s)
}
func (s String) Get(r *Runtime, key Value) Value {
switch {
case key.IsInt():
index := int(key.ToInt())
if index < 0 {
return Null
}
i := 0
start := -1
for j := range string(s) {
if i == index {
start = j
}
if i == index+1 {
return String(string(s)[start:j])
}
i++
}
if start == -1 {
return Null
}
return String(string(s)[start:])
case key.IsString():
switch key.ToString() {
case "length":
return Int(int64(utf8.RuneCountInString(string(s))))
}
}
return Null
}