Created
August 13, 2024 02:58
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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