Skip to content

refactor: replace custom sort types with slices.SortFunc - #9

Closed
ryans-posthog wants to merge 1 commit into
masterfrom
refactor/use-slices-sortfunc-for-browse-sorting
Closed

ryans-posthog wants to merge 1 commit into
masterfrom
refactor/use-slices-sortfunc-for-browse-sorting

Conversation

@ryans-posthog

Copy link
Copy Markdown
Owner

Summary

  • Replace four custom sort types (byName, byNameDirFirst, bySize, byTime) and their Len/Swap/Less boilerplate with slices.SortFunc calls
  • Remove the "sort" import since slices was already in use
  • Net reduction of 29 lines while preserving identical sorting behavior

Test plan

  • Verify go build ./modules/caddyhttp/fileserver/... compiles cleanly
  • Verify go test ./modules/caddyhttp/fileserver/... passes
  • Verify go test ./caddytest/... integration tests pass
  • Manual: browse a file listing and confirm sort by name, size, time work in both asc/desc order

Generated-By: PostHog Code
Task-Id: 8eab9f21-ca28-4327-993f-25dfd950583c

Replace four custom sort types (byName, byNameDirFirst, bySize, byTime)
and their Len/Swap/Less boilerplate with slices.SortFunc calls. Remove
the "sort" import since "slices" was already in use.

Generated-By: PostHog Code
Task-Id: 8eab9f21-ca28-4327-993f-25dfd950583c

@ryans-posthog ryans-posthog left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check up on all the failures and look at my comments.

Comment on lines +229 to 272
case sortByNameDirFirst:
cmp = func(a, b fileInfo) int {
if a.IsDir != b.IsDir {
if a.IsDir {
return -1
}
return 1
}
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
}
case sortBySize:
cmp = func(a, b fileInfo) int {
const directoryOffset = -1 << 31
aSize, bSize := a.Size, b.Size
if a.IsDir {
aSize = directoryOffset
}
if b.IsDir {
bSize = directoryOffset
}
if a.IsDir && b.IsDir {
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
}
if aSize < bSize {
return -1
}
if aSize > bSize {
return 1
}
return 0
}
case sortByTime:
cmp = func(a, b fileInfo) int {
return a.ModTime.Compare(b.ModTime)
}
}
if cmp != nil {
if l.Order == "desc" {
slices.SortFunc(l.Items, func(a, b fileInfo) int { return cmp(b, a) })
} else {
slices.SortFunc(l.Items, cmp)
}
}

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code is significantly more complex and harder to read than the original code. It's reduced the LoC but increased the complexity of understanding the code itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant