-
Notifications
You must be signed in to change notification settings - Fork 109
feat: laravel collection #1134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
feat: laravel collection #1134
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #1134 +/- ##
==========================================
+ Coverage 66.81% 69.22% +2.40%
==========================================
Files 214 266 +52
Lines 14050 16833 +2783
==========================================
+ Hits 9387 11652 +2265
- Misses 4287 4685 +398
- Partials 376 496 +120 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
support/collect/collection.go
Outdated
| return &Collection[T]{items: flattened} | ||
| } | ||
|
|
||
| func Collect[T any](items []T) *Collection[T] { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about changing collect.Collect to collect.Of? This way, it avoids redundancy and becomes more concise.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR implements a comprehensive Laravel-style collection library for Go, providing both eager (Collection) and lazy (LazyCollection) evaluation strategies with over 100 methods for data manipulation.
Key Changes:
- Introduces generic Collection and LazyCollection types with extensive method sets
- Implements Laravel-style Where filtering with multiple parameter patterns
- Provides lazy evaluation support for efficient processing of large datasets
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 7 comments.
| File | Description |
|---|---|
support/collect/collection.go |
Core eager collection implementation with 100+ methods for filtering, mapping, sorting, and aggregation operations |
support/collect/collection_test.go |
Comprehensive test suite covering all collection methods with edge cases and error scenarios |
support/collect/lazy_collection.go |
Lazy evaluation implementation using channels and goroutines for efficient streaming operations |
support/collect/lazy_collection_test.go |
Test suite for lazy collection functionality including performance tests and lazy evaluation validation |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| } | ||
| result = append(result, []T{item1, item2}) | ||
| } | ||
|
|
Copilot
AI
Nov 29, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential goroutine leak: The Zip method may leave the ch2 channel's goroutine running if ch1 completes first. After breaking from the loop at line 855, any remaining items in ch2 won't be consumed, potentially blocking the goroutine that's feeding it.
Consider draining ch2 after the loop:
// Drain remaining items from ch2 to prevent goroutine leak
for range ch2 {
}| // Drain remaining items from ch2 to prevent goroutine leak | |
| for range ch2 { | |
| } |
| func (lc *LazyCollection[T]) Take(n int) *LazyCollection[T] { | ||
| newPipeline := make([]func(<-chan T) <-chan T, len(lc.pipeline)) | ||
| copy(newPipeline, lc.pipeline) | ||
|
|
||
| newPipeline = append(newPipeline, func(input <-chan T) <-chan T { | ||
| output := make(chan T) | ||
| go func() { | ||
| defer close(output) | ||
| taken := 0 | ||
| for item := range input { | ||
| if taken >= n { | ||
| break | ||
| } | ||
| output <- item | ||
| taken++ | ||
| } | ||
| }() | ||
| return output | ||
| }) |
Copilot
AI
Nov 29, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential goroutine leak: When Take breaks early at line 669, the input channel may not be fully consumed, which could block upstream goroutines. This is a common issue in lazy evaluation pipelines.
Consider draining the input channel after breaking:
for item := range input {
if taken >= n {
// Drain remaining items to prevent blocking upstream
for range input {
}
break
}
output <- item
taken++
}| func (lc *LazyCollection[T]) TakeWhile(predicate func(T) bool) *LazyCollection[T] { | ||
| newPipeline := make([]func(<-chan T) <-chan T, len(lc.pipeline)) | ||
| copy(newPipeline, lc.pipeline) | ||
|
|
||
| newPipeline = append(newPipeline, func(input <-chan T) <-chan T { | ||
| output := make(chan T) | ||
| go func() { | ||
| defer close(output) | ||
| for item := range input { | ||
| if !predicate(item) { | ||
| break | ||
| } | ||
| output <- item | ||
| } | ||
| }() | ||
| return output | ||
| }) |
Copilot
AI
Nov 29, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential goroutine leak: Similar to Take, when TakeWhile breaks early at line 694, the input channel may not be fully consumed, potentially blocking upstream goroutines.
Consider draining the input channel after breaking to prevent goroutine leaks.
| func (lc *LazyCollection[T]) Some(predicate func(T) bool) bool { | ||
| ch := lc.execute() | ||
| for item := range ch { | ||
| if predicate(item) { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } |
Copilot
AI
Nov 29, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential goroutine leak: When Some returns early at line 617, the remaining items in the channel won't be consumed, potentially blocking upstream goroutines.
Consider draining the channel after returning true:
if predicate(item) {
// Drain to prevent blocking
go func() { for range ch {} }()
return true
}| func (lc *LazyCollection[T]) First() *T { | ||
| ch := lc.execute() | ||
| for item := range ch { | ||
| return &item | ||
| } | ||
| return nil | ||
| } |
Copilot
AI
Nov 29, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential goroutine leak: When First returns early at line 248, remaining items in the channel won't be consumed, potentially blocking upstream goroutines. Similar issue exists in FirstWhere (lines 261-268) and Every (lines 210-218).
Consider draining the channel after early returns.
| func (c *Collection[T]) Zip(other *Collection[T]) [][]T { | ||
| maxLen := len(c.items) | ||
| if len(other.items) > maxLen { | ||
| maxLen = len(other.items) | ||
| } | ||
|
|
||
| var result [][]T | ||
| for i := 0; i < maxLen; i++ { | ||
| var pair []T | ||
| if i < len(c.items) { | ||
| pair = append(pair, c.items[i]) | ||
| } | ||
| if i < len(other.items) { | ||
| pair = append(pair, other.items[i]) | ||
| } | ||
| result = append(result, pair) | ||
| } | ||
|
|
||
| return result | ||
| } |
Copilot
AI
Nov 29, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The Zip method in Collection includes partial pairs when collections have different lengths, while LazyCollection.Zip stops at the shorter collection. This inconsistency in behavior could confuse users.
Collection.Zip produces: [[1], [2, 3]] for [1, 2] and [3]
LazyCollection.Zip produces: [] for the same inputs
Consider making the behavior consistent between both implementations. The Laravel-style typically stops at the shorter collection (like LazyCollection does).
| return &Collection[interface{}]{items: mapped} | ||
| } | ||
|
|
||
| // MapCollect it will be renamed to Map in next release |
Copilot
AI
Nov 29, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Grammar issue: "it will be renamed" should be "It will be renamed" (capitalize first letter of sentence).
| // MapCollect it will be renamed to Map in next release | |
| // MapCollect It will be renamed to Map in next release |
hwbrzzl
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Amazing PR 👍 @ahmed3mar Could you confirm the Copilot comments? Basically, LGTM.
| func (it *lazyIterator[T]) Reset() { | ||
| it.done = false | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the function can be used as expect when it.ch is closed, could you confirm this and add a test case for it?
| taken := 0 | ||
| for item := range input { | ||
| if taken >= n { | ||
| break |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There may still be data in the input chan, but break directly. goroutine will leak. The same as TakeWhile
| defer close(output) | ||
| seen := make(map[string]bool) | ||
| for item := range input { | ||
| key := fmt.Sprintf("%v", item) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The key will duplicated when item is struct or map, is there a better way to deal with such situation?
| ch1 := lc.execute() | ||
| ch2 := other.execute() | ||
|
|
||
| for item1 := range ch1 { | ||
| item2, ok2 := <-ch2 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The same as above, ch1 and ch2 may be leak.
| ch1 := lc.execute() | |
| ch2 := other.execute() | |
| for item1 := range ch1 { | |
| item2, ok2 := <-ch2 | |
| ch1 := lc.execute() | |
| ch2 := other.execute() | |
| defer func() { | |
| go func() { for range ch1 {} }() | |
| go func() { for range ch2 {} }() | |
| }() | |
| for item1 := range ch1 { | |
| item2, ok2 := <-ch2 |
| seen[key] = true | ||
| } | ||
| } | ||
| return &Collection[T]{items: duplicates} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the collecction is 3,3,3, duplicates will be 3,3. It's unexpected.
| var duplicates []T | ||
|
|
||
| for _, item := range c.items { | ||
| key := fmt.Sprintf("%v", item) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The same as LazyCollection, %v is unused for struct and map.
krishankumar01
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The implementation and the wide range of methods are solid. Instead of implementing everything in a single PR, should we break it into smaller PRs so that reviewing becomes easier?
cc: @hwbrzzl
| return 0 | ||
| } | ||
|
|
||
| max := keyFunc(c.items[0]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about renaming this variable to something else, since it collides with Go’s built-in max method (and similarly for min)?
| if len(c.items) == 0 { | ||
| return nil | ||
| } | ||
| rng := rand.New(rand.NewSource(time.Now().UnixNano())) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Initializing a random generator every time is slower. How about we initialize a global generator and reuse it? And why this method is returning a pointer of type T?
|
|
||
| func Reduce[T, R any](c *Collection[T], fn func(R, T, int) R, initial R) R { | ||
| result := initial | ||
| for i, item := range c.items { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about we keep the input order as the index and use the remaining arguments for the fn(same for all the places where we pass index in function)?
| return -1 | ||
| } | ||
|
|
||
| func (c *Collection[T]) Shift() *T { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why return a pointer to a generic type? If the user needs a pointer, they can simply assign T as a pointer type anyway, right? Can we fix similar issue in other methods also?
| shuffled := make([]T, len(c.items)) | ||
| copy(shuffled, c.items) | ||
|
|
||
| rng := rand.New(rand.NewSource(time.Now().UnixNano())) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ditto
| start = len(c.items) | ||
| } | ||
|
|
||
| end := start + deleteCount |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What if the user accidentally passes a negative deleteCount? It would end up duplicating the elements, right?
| for i, item := range c.items { | ||
| c.items[i] = fn(item, i) | ||
| } | ||
| return c |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why do we return the original collection in some places and create a new one in others? How about always returning a new collection so the user has fewer surprises? For example, Transform also modifies the original if that's the expected behavior, how about documenting it?
| func (c *Collection[T]) Union(other *Collection[T]) *Collection[T] { | ||
| existing := make(map[string]bool) | ||
| for _, item := range c.items { | ||
| existing[fmt.Sprintf("%v", item)] = true |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is very performance-heavy. For example, if T is a large User object, checking it this way will be significantly slower. In any case, we should not use the fmt package for key generation. For example:
type BigUser struct {
ID int
Name string
Bio string // Long text
Metadata map[string]string
}
// IF YOU USE fmt.Sprintf("%v", user):
// 1. Go has to reflectively walk through ID, Name, Bio, and the Map.
// 2. It allocates a massive string for EVERY user.
// 3. It compares massive strings.
// IF YOU USE a proper Key (User.ID):
// 1. Go compares one integer.
// 2. Zero allocation.
// 3. Instant.So maybe we can accept a keyFunc as well, right? Also, this issue exists in every method that checks for seen and uses fmt.
| } | ||
| } | ||
|
|
||
| func (c *Collection[T]) WhereIn(field string, values []interface{}) *Collection[T] { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using this method will be a lot harder than expected because every time we use it we will need to convert the values to []any which a lot of pain, workaround would be to accept it like ...any.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hmm make sense
|
|
||
| switch operator { | ||
| case "=", "==": | ||
| return reflect.DeepEqual(*fieldValue, value) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is an issue or inconsistent behaviour, for example:
func main() {
p := Product{Price: 100}
c := Of([]Product{p})
// "100" (int) > "50" (string) -> True
fmt.Println(c.Where("Price", ">", "50").Count()) // Output: 1 (Found)
// "100" (int) == "100" (string) -> False
fmt.Println(c.Where("Price", "=", "100").Count()) // Output: 0 (Not Found!)
}|
I recommend against merging methods that are ambiguous, handle edge cases incorrectly, or introduce significant performance bottlenecks. It is better to omit these features than to expose unsafe or unoptimized implementations. |
Yes, we recommend multiple small PRs instead of a big one. It's hard to review it. We can follow this next time. |



📑 Description
Closes goravel/goravel#566
Basic Usage
Creating Collections
Basic Operations
Filtering and Mapping
Aggregation Methods
Conditional Operations
Available Methods
Core Methods (Alphabetical)
After(value)- Get item after given valueAll()- Get all items as sliceAverage(keyFunc)- Calculate average using key functionBefore(value)- Get item before given valueChunk(size)- Split into chunks of given sizeClone()- Create a copy of the collectionCollapse()- Collapse nested arrays into single arrayCombine(keys)- Combine with keys to create mapContains(value)- Check if collection contains valueCount()- Get item countDiff(other)- Get difference with another collectionEach(func)- Iterate over each itemEvery(predicate)- Check if all items match predicateFilter(predicate)- Filter items by predicateFirst()- Get first itemFlatten()- Flatten nested structuresGroupBy(keyFunc)- Group items by key functionIntersect(other)- Get intersection with another collectionIsEmpty()- Check if collection is emptyIsNotEmpty()- Check if collection is not emptyJoin(separator)- Join items with separatorLast()- Get last itemMap(func)- Transform each item with a function (returns Collection[interface{}])Merge(other)- Merge with another collectionPartition(predicate)- Split into two collections by predicatePluck(field)- Extract field valuesPush(items...)- Add items to endReverse()- Reverse orderSearch(value)- Find index of valueSlice(start, length)- Get slice of itemsSort(lessFunc)- Sort by comparison functionSortBy(keyFunc)- Sort by key functionSum(keyFunc)- Calculate sum using key functionTake(n)- Take first n itemsUnique()- Get unique itemsWhere(field, operator, value)- Filter by field comparisonZip(other)- Zip with another collectionWhere Method - Laravel-style Filtering
The
Wheremethod supports multiple patterns for flexible filtering:Supported Operators:
=,==- Equality!=- Inequality>,>=- Greater than, Greater than or equal<,<=- Less than, Less than or equallike- Case-insensitive substring matchnot like- Case-insensitive substring exclusionUtility Methods
Debug()- Print collection contentsDump()- Print collection contentsTap(func)- Execute function and return collectionToJSON()- Convert to JSON stringWhen(condition, func)- Execute function if condition is trueUnless(condition, func)- Execute function if condition is falseMap Method - Laravel-style Transformation
The
Mapmethod provides Laravel-style transformation capabilities:Generic Functions
Some operations require type transformation and are provided as generic functions for type safety:
Testing
go test -vExamples
See
example_test.gofor comprehensive usage examples.LazyCollection
LazyCollection provides lazy evaluation for efficient processing of large datasets. Operations are not executed until a terminal operation is called.
Creating LazyCollections
Lazy Operations
Performance Benefits
Lazy vs Eager
Converting Between Collections
LazyCollection Methods
All()- Materialize all itemsCount()- Count itemsFilter(predicate)- Filter itemsMap(func)- Transform each item with a function (returns LazyCollection[interface{}])Where(params...)- Laravel-style filtering (supports all same patterns as Collection)Take(n)- Take first n itemsSkip(n)- Skip first n itemsTakeWhile(predicate)- Take while condition is trueDropWhile(predicate)- Drop while condition is trueUnique()- Get unique itemsSort(lessFunc)- Sort itemsReverse()- Reverse orderSum(keyFunc)- Calculate sumAverage(keyFunc)- Calculate averageMin(keyFunc)- Find minimumMax(keyFunc)- Find maximumGroupBy(keyFunc)- Group itemsPartition(predicate)- Split into two collectionsFlatMap(func)- Flat map transformationEach(func)- Execute function for each itemForEach(func)- Execute function for each item (consumes collection)Iterator()- Get iterator for manual controlCollect()- Convert to eager CollectionLicense
MIT License
✅ Checks