floats: add Truncate method support to floats slice

This commit is contained in:
c9s 2023-06-01 08:11:19 +08:00
parent 9e6cb0858e
commit 47e869a9f7
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 17 additions and 5 deletions

View File

@ -191,14 +191,18 @@ func (s Slice) Last(i int) float64 {
return s[length-1-i]
}
func (s Slice) Truncate(size int) Slice {
if len(s) < size {
return s
}
return s[len(s)-size:]
}
// Index fetches the element from the end of the slice
// WARNING: it does not start from 0!!!
func (s Slice) Index(i int) float64 {
length := len(s)
if i < 0 || length-1-i < 0 {
return 0.0
}
return s[length-1-i]
return s.Last(i)
}
func (s Slice) Length() int {

View File

@ -15,6 +15,14 @@ func TestSub(t *testing.T) {
assert.Equal(t, 5, c.Length())
}
func TestTruncate(t *testing.T) {
a := New(1, 2, 3, 4, 5)
for i := 5; i > 0; i-- {
a = a.Truncate(i)
assert.Equal(t, i, a.Length())
}
}
func TestAdd(t *testing.T) {
a := New(1, 2, 3, 4, 5)
b := New(1, 2, 3, 4, 5)