-
-
Notifications
You must be signed in to change notification settings - Fork 837
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
Feat: Adding the equivalent of checking if two slices are the same #498
base: master
Are you sure you want to change the base?
Changes from 2 commits
776a207
c46d570
aa1627f
e72361b
e8667ba
c1b28e7
cfaeb62
4450609
c0a950b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -44,6 +44,28 @@ func EveryBy[T any](collection []T, predicate func(item T) bool) bool { | |
return true | ||
} | ||
|
||
// Equivalent Returns true if the subset has the same elements and the same number of each element as the collection. | ||
func Equivalent[T comparable](collection, subset []T) bool { | ||
l := len(collection) | ||
if l != len(subset) { | ||
return false | ||
} | ||
|
||
var m = make(map[T]int, l) | ||
for i := range collection { | ||
m[collection[i]] += 1 | ||
} | ||
for i := range subset { | ||
m[subset[i]] -= 1 | ||
} | ||
for _, v := range m { | ||
if v != 0 { | ||
return false | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Your logic requires extra space in the map and also 3 times iterating over the map. What are your thoughts ?? Also after adding the function, you can add the function to Readme also. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because just I have added doc and removed an unessential iterating based on your suggestion. |
||
return true | ||
} | ||
|
||
// Some returns true if at least 1 element of a subset is contained into a collection. | ||
// If the subset is empty Some returns false. | ||
func Some[T comparable](collection []T, subset []T) bool { | ||
|
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.
Following #498 (comment)
Maybe this name would be more appropriate