Skip to content

Instantly share code, notes, and snippets.

@matthewoestreich
Created August 13, 2024 02:58
Show Gist options
  • Save matthewoestreich/6264f9f422432adafbaa0b9a38c69adc to your computer and use it in GitHub Desktop.
Save matthewoestreich/6264f9f422432adafbaa0b9a38c69adc to your computer and use it in GitHub Desktop.
Generic slice filter in Go with similar behavior to `[].filter((i, e) => bool)` in JS.
type filterFunc[T any] func(int, T) bool
func filter[T any](arr []T, fn filterFunc[T]) []T {
filtered := []T{}
for i, e := range arr {
if fn(i, e) {
filtered = append(filtered, e)
}
}
return filtered
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment