Last active
August 20, 2019 02:57
-
-
Save wangpin34/ff82b7750e07002445f7991ee80f8a08 to your computer and use it in GitHub Desktop.
golang list: general helper functions
This file contains 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
/* | |
* | |
* 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