-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnumber.go
90 lines (78 loc) · 2.54 KB
/
number.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
package gates
import (
"math"
"strconv"
)
type Int int64
type Float float64
type Number interface {
Value
number()
}
func (Int) number() {}
func (Float) number() {}
func (Int) IsString() bool { return false }
func (Int) IsInt() bool { return true }
func (Int) IsFloat() bool { return false }
func (i Int) ToNumber() Number { return i }
func (Int) IsBool() bool { return false }
func (Int) IsFunction() bool { return false }
func (i Int) ToString() string { return strconv.FormatInt(int64(i), 10) }
func (i Int) ToInt() int64 { return int64(i) }
func (i Int) ToFloat() float64 { return float64(i) }
func (i Int) ToBool() bool { return int64(i) != 0 }
func (i Int) ToFunction() Function { return _EmptyFunction }
func (i Int) ToNative(...ToNativeOption) interface{} { return i.ToInt() }
func (i Int) Equals(other Value) bool {
switch {
case other.IsInt():
return i.ToInt() == other.ToInt()
case other.IsFloat():
return i.ToFloat() == other.ToFloat()
case other.IsString():
return other.ToNumber().Equals(i)
case other.IsBool():
return i.ToInt() == other.ToInt()
}
return false
}
func (i Int) SameAs(b Value) bool {
ib, ok := b.(Int)
if !ok {
return false
}
return i == ib
}
func (Float) IsString() bool { return false }
func (Float) IsInt() bool { return false }
func (Float) IsFloat() bool { return true }
func (f Float) ToNumber() Number { return f }
func (Float) IsBool() bool { return false }
func (Float) IsFunction() bool { return false }
func (f Float) ToString() string { return strconv.FormatFloat(float64(f), 'g', -1, 64) }
func (f Float) ToInt() int64 { return int64(f) }
func (f Float) ToFloat() float64 { return float64(f) }
func (f Float) ToBool() bool { return float64(f) != 0 && !math.IsNaN(float64(f)) }
func (f Float) ToFunction() Function { return _EmptyFunction }
func (f Float) ToNative(...ToNativeOption) interface{} { return f.ToFloat() }
func (f Float) Equals(other Value) bool {
switch {
case other.IsInt():
return f.ToFloat() == other.ToFloat()
case other.IsFloat():
return f.ToFloat() == other.ToFloat()
case other.IsString():
return other.ToNumber().Equals(f)
case other.IsBool():
return f.ToInt() == other.ToInt()
default:
return false
}
}
func (f Float) SameAs(b Value) bool {
fb, ok := b.(Float)
if !ok {
return false
}
return f == fb
}