Skip to content

Instantly share code, notes, and snippets.

@wangpin34
Last active August 20, 2019 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wangpin34/ff82b7750e07002445f7991ee80f8a08 to your computer and use it in GitHub Desktop.
Save wangpin34/ff82b7750e07002445f7991ee80f8a08 to your computer and use it in GitHub Desktop.
golang list: general helper functions
/*
*
* Demo: https://repl.it/@wangpin34/array-utils
*/
/*
* Filter elements which pass the test function
*/
func filter(in interface{}, testFunc func(interface{}) bool) *[]interface{} {
b, _ := json.Marshal(in)
array := make([]interface{}, 0, 10)
err := json.Unmarshal(b, &array)
if err == nil {
s := make([]interface{}, 0, len(array))
for _, value := range array {
if testFunc(value) == true {
s = append(s, value)
}
}
return &s
}
fmt.Printf("Error while filter elements: %s \n", err.Error())
return nil
}
/*
* Find the first element which pass the test function, if no element pass, return nil
*/
func find(in interface{}, testFunc func(interface{}) bool) *interface{} {
b, _ := json.Marshal(in)
array := make([]interface{}, 0, 10)
err := json.Unmarshal(b, &array)
if err == nil {
for _, value := range array {
if testFunc(value) == true {
return &value
}
}
}
return nil
}
/*
* Find the index of first element which pass the test function, if no element pass, return -1
*/
func findIndex(in interface{}, testFunc func(interface{}) bool) int {
b, _ := json.Marshal(in)
array := make([]interface{}, 0, 10)
err := json.Unmarshal(b, &array)
if err == nil {
for index, value := range array {
if testFunc(value) == true {
return index
}
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment