This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
e621-sdk-go/pkg/e621/utils/helper.go
SoXX 8c662f78fd docs: added more & unified documentation format
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 14:41:16 +01:00

54 lines
1.4 KiB
Go

package utils
import (
"encoding/json"
"os"
)
// SliceFilter filters elements of a generic type from a slice based on a provided filter function.
//
// Parameters:
// - slice: The input slice containing elements of type T.
// - filter: A function that takes an element of type T and returns a boolean indicating whether to include the element in the result.
//
// Returns:
// - ret: A slice containing elements that satisfy the filtering condition.
func SliceFilter[T any](slice []T, filter func(T) bool) (ret []T) {
for _, s := range slice {
if filter(s) {
ret = append(ret, s)
}
}
return
}
// LoadJsonTestData decodes JSON data from a file and populates a variable of a generic type T.
//
// Parameters:
// - testDataPath: The file path to the JSON data.
//
// Returns:
// - T: A variable of type T populated with the decoded JSON data.
// - error: An error, if any, encountered during file opening, decoding, or closing.
func LoadJsonTestData[T any](testDataPath string) (T, error) {
// Create a variable to store the decoded JSON data
var jsonData T
// Open the JSON file
file, err := os.Open(testDataPath)
if err != nil {
return jsonData, err
}
defer file.Close()
// Create a decoder
decoder := json.NewDecoder(file)
// Decode the JSON data into the struct
if err := decoder.Decode(&jsonData); err != nil {
return jsonData, err
}
return jsonData, nil
}