1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-30 06:59:03 +01:00

Match Liquid/Ruby array[float]

This commit is contained in:
Oliver Steele 2017-07-21 16:23:08 -04:00
parent 8040e9ee3a
commit fa5de60b78
2 changed files with 19 additions and 7 deletions

View File

@ -148,13 +148,23 @@ func (v structValue) Contains(elem Value) bool {
func (v arrayValue) IndexValue(index Value) Value { func (v arrayValue) IndexValue(index Value) Value {
rv := reflect.ValueOf(v.basis) rv := reflect.ValueOf(v.basis)
if n, ok := index.Interface().(int); ok { var n int
if n < 0 { switch ix := index.Interface().(type) {
n += rv.Len() case int:
} n = ix
if 0 <= n && n < rv.Len() { case float32:
return ValueOf(rv.Index(n).Interface()) // 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 return nilValue
} }

View File

@ -53,6 +53,8 @@ func TestValue_IndexValue(t *testing.T) {
av := ValueOf([]string{"first", "second", "third"}) av := ValueOf([]string{"first", "second", "third"})
require.Equal(t, "first", av.IndexValue(ValueOf(0)).Interface()) require.Equal(t, "first", av.IndexValue(ValueOf(0)).Interface())
require.Equal(t, "third", av.IndexValue(ValueOf(-1)).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"}) hv := ValueOf(map[string]interface{}{"key": "value"})
require.Equal(t, "value", hv.IndexValue(ValueOf("key")).Interface()) require.Equal(t, "value", hv.IndexValue(ValueOf("key")).Interface())