mirror of
https://github.com/danog/liquid.git
synced 2024-11-26 23:24:38 +01:00
Match Liquid/Ruby array[float]
This commit is contained in:
parent
8040e9ee3a
commit
fa5de60b78
@ -148,14 +148,24 @@ func (v structValue) Contains(elem Value) bool {
|
||||
|
||||
func (v arrayValue) IndexValue(index Value) Value {
|
||||
rv := reflect.ValueOf(v.basis)
|
||||
if n, ok := index.Interface().(int); ok {
|
||||
var n int
|
||||
switch ix := index.Interface().(type) {
|
||||
case int:
|
||||
n = ix
|
||||
case float32:
|
||||
// this how Ruby arrays, and therefore Liquid arrays, work
|
||||
n = int(ix)
|
||||
case float64:
|
||||
n = int(ix)
|
||||
default:
|
||||
return nilValue
|
||||
}
|
||||
if n < 0 {
|
||||
n += rv.Len()
|
||||
}
|
||||
if 0 <= n && n < rv.Len() {
|
||||
return ValueOf(rv.Index(n).Interface())
|
||||
}
|
||||
}
|
||||
return nilValue
|
||||
}
|
||||
|
||||
|
@ -53,6 +53,8 @@ func TestValue_IndexValue(t *testing.T) {
|
||||
av := ValueOf([]string{"first", "second", "third"})
|
||||
require.Equal(t, "first", av.IndexValue(ValueOf(0)).Interface())
|
||||
require.Equal(t, "third", av.IndexValue(ValueOf(-1)).Interface())
|
||||
require.Equal(t, "second", av.IndexValue(ValueOf(1.0)).Interface())
|
||||
require.Equal(t, "second", av.IndexValue(ValueOf(1.1)).Interface())
|
||||
|
||||
hv := ValueOf(map[string]interface{}{"key": "value"})
|
||||
require.Equal(t, "value", hv.IndexValue(ValueOf("key")).Interface())
|
||||
|
Loading…
Reference in New Issue
Block a user