1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-26 21:14:45 +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 {
rv := reflect.ValueOf(v.basis)
if n, ok := index.Interface().(int); ok {
if n < 0 {
n += rv.Len()
}
if 0 <= n && n < rv.Len() {
return ValueOf(rv.Index(n).Interface())
}
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
}

View File

@ -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())