Skip to content

Commit

Permalink
fix: top list
Browse files Browse the repository at this point in the history
  • Loading branch information
dundee committed Dec 1, 2024
1 parent 3f37bc1 commit a8b32c9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
11 changes: 3 additions & 8 deletions pkg/analyze/top.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,13 @@ func NewTopList(count int) *TopList {

// Add adds file to the list
func (tl *TopList) Add(file fs.Item) {
if len(tl.Items) < tl.Count {
if file.GetSize() > tl.MinSize || len(tl.Items) < tl.Count {
tl.Items = append(tl.Items, file)
if file.GetSize() > tl.MinSize {
tl.MinSize = file.GetSize()
}
} else if file.GetSize() > tl.MinSize {
tl.Items = append(tl.Items, file)
tl.MinSize = file.GetSize()
sort.Sort(fs.ByApparentSize(tl.Items))
if len(tl.Items) > tl.Count {
sort.Sort(fs.ByApparentSize(tl.Items))
tl.Items = tl.Items[1:]
}
tl.MinSize = tl.Items[0].GetSize()
}
}

Expand Down
31 changes: 31 additions & 0 deletions pkg/analyze/top_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package analyze

import (
"sort"
"testing"

"github.com/dundee/gdu/v5/internal/testdir"
"github.com/dundee/gdu/v5/pkg/fs"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -36,3 +38,32 @@ func TestCollectTopFiles1(t *testing.T) {
assert.Equal(t, "file", topFiles[0].GetName())
assert.Equal(t, int64(5), topFiles[0].GetSize())
}

func TestAdd2(t *testing.T) {
topList := NewTopList(2)
topList.Add(&File{Size: 1, Name: "file1"})
topList.Add(&File{Size: 5, Name: "file5"})
topList.Add(&File{Size: 2, Name: "file2"})

sort.Sort(sort.Reverse(fs.ByApparentSize(topList.Items)))

assert.Equal(t, 2, len(topList.Items))
assert.Equal(t, "file5", topList.Items[0].GetName())
assert.Equal(t, "file2", topList.Items[1].GetName())
}

func TestAdd3(t *testing.T) {
topList := NewTopList(3)
topList.Add(&File{Size: 5, Name: "file5"})
topList.Add(&File{Size: 1, Name: "file1"})
topList.Add(&File{Size: 2, Name: "file2"})
topList.Add(&File{Size: 4, Name: "file4"})
topList.Add(&File{Size: 3, Name: "file3"})

sort.Sort(sort.Reverse(fs.ByApparentSize(topList.Items)))

assert.Equal(t, 3, len(topList.Items))
assert.Equal(t, "file5", topList.Items[0].GetName())
assert.Equal(t, "file4", topList.Items[1].GetName())
assert.Equal(t, "file3", topList.Items[2].GetName())
}

0 comments on commit a8b32c9

Please sign in to comment.