devtoolkit

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 30, 2023 License: MIT Imports: 10 Imported by: 3

README

Devtoolkit

Go Report Card Go Reference Release

Devtoolkit is a powerful and ever-expanding toolkit designed to streamline daily tasks in Golang software development. Within this library, you'll find an array of features, such as tools for working with yml or json prop files, slices, handling generic objects, managing concurrency, and more. As Devtoolkit continues to evolve, it will encompass even more functionalities to cater to a variety of programming needs.

Table of Contents

Installation

go get github.com/rendis/devtoolkit

Usage

Working with Concurrency

For handling concurrency, devtoolkit provides a ConcurrentExec type that allows to execute a series of functions concurrently. The library offers a convenient way to manage concurrent execution, allowing to cancel execution, retrieve results and errors, and check when execution is done.

Creating and running concurrent functions

Here's an example of how to create and run concurrent functions with ConcurrentExec.

var fns []devtoolkit.ConcurrentFn

fns = append(fns, func(ctx context.Context) (any, error) {
   // Implement function logic
   return "Result1", nil
})

fns = append(fns, func(ctx context.Context) (any, error) {
   // Implement function logic
   return "Result2", nil
})

ctx := context.Background()
ce, err := devtoolkit.NewConcurrentExec().ExecuteFns(ctx, fns...)

if err != nil {
   fmt.Println(err)
}

// errors is a slice of errors returned by the functions, where each index corresponds to the function at the same index in the fns slice
errors := ce.Errors()
for _, err := range errors {
   if err != nil {
      fmt.Println(err)
   }
}

// results is a slice of results returned by the functions, where each index corresponds to the function at the same index in the fns slice
// Note: results are of type any, so you'll need to cast them to the appropriate type
results := ce.Results()
for _, res := range results {
   fmt.Println(res)
}

Note: This example does not include error handling, be sure to do so in your implementations.


Load Configuration Propertieswith Environment Variables

Utility functions for loading configuration properties from JSON or YAML files. This functionality supports the injection of environment variables directly into the configuration properties.

dbConfig:
  host: ${DB_HOST}
  port: ${DB_PORT}
  username: ${DB_USERNAME}
  password: ${DB_PASSWORD}
  description: "YAML config file"
{
  "dbConfig": {
    "host": "${DB_HOST}",
    "port": "${DB_PORT}",
    "username": "${DB_USERNAME}",
    "password": "${DB_PASSWORD}",
    "description": "JSON config file"
  }
}
type Config struct {
    DBConfig `json:"dbConfig" yaml:"dbConfig"`
}

type DBConfig struct {
    Host string `json:"host" yaml:"host"`
    Port int `json:"port" yaml:"port"`
    Username string `json:"username" yaml:"username"`
    Password string `json:"password" yaml:"password"`
    Description string `json:"description" yaml:"description"`
}

cfg := &Config{}
err := devtoolkit.LoadPropFile("config.json", cfg)

Working with Generic Objects
ToPtr

The ToPtr function takes a value of any type and returns a pointer to it.

val := 5
ptr := devtoolkit.ToPtr(val)
fmt.Println(*ptr) // Returns 5
IsZero

The IsZero function checks whether a value is the zero value of its type.

fmt.Println(devtoolkit.IsZero(0)) // Returns true
fmt.Println(devtoolkit.IsZero(1)) // Returns false
fmt.Println(devtoolkit.IsZero("")) // Returns true

Working with Slices
Contains

The Contains function checks whether a slice contains an item. The item must be comparable.

func Contains[T comparable](slice []T, item T) bool

Example:

slice := []int{1, 2, 3}
item := 2
fmt.Println(devtoolkit.Contains(slice, item)) // Returns true
ContainsWithPredicate

The ContainsWithPredicate function checks whether a slice contains an item using a predicate to compare items.

func ContainsWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) bool

Example:

slice := []int{1, 2, 3}
item := 2
predicate := func(a, b int) bool { return a == b }
fmt.Println(devtoolkit.ContainsWithPredicate(slice, item, predicate)) // Returns true
IndexOf

IndexOf returns the index of the first instance of an item in a slice, or -1 if the item is not present in the slice.

func IndexOf[T comparable](slice []T, item T) int

Example:

index := IndexOf([]int{1, 2, 3, 2, 1}, 2)
fmt.Println(index) // Output: 1
IndexOfWithPredicate

IndexOfWithPredicate returns the index of the first instance of an item in a slice, or -1 if the item is not present in the slice. It uses a predicate function to compare items.

func IndexOfWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) int

Example:

index := IndexOfWithPredicate([]string{"apple", "banana", "cherry"}, "APPLE", strings.EqualFold)
fmt.Println(index) // Output: 0
LastIndexOf

LastIndexOf returns the index of the last instance of an item in a slice, or -1 if the item is not present in the slice.

func LastIndexOf[T comparable](slice []T, item T) int

Example:

index := LastIndexOf([]int{1, 2, 3, 2, 1}, 2)
fmt.Println(index) // Output: 3
LastIndexOfWithPredicate

LastIndexOfWithPredicate returns the index of the last instance of an item in a slice, or -1 if the item is not present in the slice. It uses a predicate function to compare items.

func LastIndexOfWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) int

Example:

index := LastIndexOfWithPredicate([]string{"apple", "banana", "cherry", "apple"}, "APPLE", strings.EqualFold)
fmt.Println(index) // Output: 3
Remove

Remove removes the first instance of an item from a slice, if present. It returns true if the item was removed, false otherwise.

func Remove[T comparable](slice []T, item T) bool

Example:

removed := Remove([]int{1, 2, 3, 2, 1}, 2)
fmt.Println(removed) // Output: true
RemoveWithPredicate

RemoveWithPredicate removes the first instance of an item from a slice, if present. It uses a predicate function to compare items. It returns true if the item was removed, false otherwise.

func RemoveWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) bool

Example:

removed := RemoveWithPredicate([]string{"apple", "banana", "cherry"}, "APPLE", strings.EqualFold)
fmt.Println(removed) // Output: true
RemoveAll

RemoveAll removes all instances of an item from a slice, if present. It returns true if the item was removed, false otherwise.

func RemoveAll[T comparable](slice []T, item T) bool

Example:

removed := RemoveAll([]int{1, 2, 3, 2, 1}, 2)
fmt.Println(removed) // Output: true
RemoveAllWithPredicate

RemoveAllWithPredicate removes all instances of an item from a slice, if present. It uses a predicate function to compare items. It returns true if the item was removed, false otherwise.

func RemoveAllWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) bool

Example:

removed := RemoveAllWithPredicate([]string{"apple", "banana", "cherry", "apple"}, "APPLE", strings.EqualFold)
fmt.Println(removed) // Output: true
RemoveAt

RemoveAt removes the item at a given index from a slice. It returns true if the item was removed, false otherwise.

func RemoveAt[T any](slice []T, index int) bool

Example:

removed := RemoveAt([]int{1, 2, 3}, 1)
fmt.Println(removed) // Output: true
RemoveRange

RemoveRange removes the items in a given range from a slice. It returns true if items were removed, false otherwise.

func RemoveRange[T any](slice []T, start, end int) bool

Example:

removed := RemoveRange([]int{1, 2, 3, 4, 5}, 1, 3)
fmt.Println(removed) // Output: true
RemoveIf

RemoveIf removes all items from a slice for which a predicate function returns true. It returns true if any items were removed, false otherwise.

func RemoveIf[T any](slice []T, predicate func(T) bool) bool

Example:

removed := RemoveIf([]int{1, 2, 3, 4, 5}, func(n int) bool { return n%2 == 0 })
fmt.Println(removed) // Output: true
Filter

Filter returns a new slice containing all items from the original slice for which a predicate function returns true.

func Filter[T any](slice []T, predicate func(T) bool) []T

Example:

filtered := Filter([]int{1, 2, 3, 4, 5}, func(n int) bool { return n%2 == 0 })
fmt.Println(filtered) // Output: [2 4]
FilterNot

FilterNot returns a new slice containing all items from the original slice for which a predicate function returns false.

func FilterNot[T any](slice []T, predicate func(T) bool) []T

Example:

filtered := FilterNot([]int{1, 2, 3, 4, 5}, func(n int) bool { return n%2 == 0 })
fmt.Println(filtered) // Output: [1 3 5]

Map

Map

applies a transformation function to all items in a slice and returns a new slice containing the results.

func Map[T, R any](slice []T, mapper func(T) R) []R 

Example:

mapped := Map([]int{1, 2, 3}, func(n int) int { return n * 2 })
fmt.Println(mapped) // Output: [2 4 6]
RemoveDuplicates

RemoveDuplicates removes all duplicate items from a slice. It returns true if any items were removed, false otherwise.

func RemoveDuplicates[T comparable](slice []T) bool

Example:

removed := RemoveDuplicates([]int{1, 2, 3, 2, 1})
fmt.Println(removed) // Output: true
Reverse

Reverse reverses the order of items in a slice.

func Reverse[T any](slice []T)

Example:

data := []int{1, 2, 3}
Reverse(data)
fmt.Println(data) // Output: [3 2 1]
Difference

Difference returns a new slice containing all items from the original slice that are not present in the other slice.

func Difference[T comparable](slice, other []T) []T

Example:

diff := Difference([]int{1, 2, 3, 4, 5}, []int{3, 4, 5, 6, 7})
fmt.Println(diff) // Output: [1 2]
Intersection

Intersection returns a new slice containing all items from the original slice that are also present in the other slice.

func Intersection[T comparable](slice, other []T) []T

Example:

inter := Intersection([]int{1, 2, 3, 4, 5}, []int{3, 4, 5, 6, 7})
fmt.Println(inter) // Output: [3 4 5]
Union

Union returns a new slice containing all unique items from both the original slice and the other slice.

func Union[T comparable](slice, other []T) []T

Example:

union := Union([]int{1, 2, 3}, []int{3, 4, 5})
fmt.Println(union) // Output: [1 2 3 4 5]

Contributions

Contributions to this library are welcome. Please open an issue to discuss the enhancement or feature you would like to add, or just make a pull request.

License

Devtoolkit is licensed under the MIT License. Please see the LICENSE file for details.

Documentation

Overview

Package devtoolkit provides a collection of utilities for Golang development.

Index

Constants

This section is empty.

Variables

View Source
var (
	ConcurrentExecAlreadyRunningErr = errors.New("concurrent fns already running")
	ConcurrentExecNilContextErr     = errors.New("context must not be nil")
	ConcurrentExecFnsNilOrEmptyErr  = errors.New("fns must not be nil or empty")
)

Error values that can be returned by ConcurrentExec.

Functions

func Contains

func Contains[T comparable](slice []T, item T) bool

Contains checks if a slice contains an item. Item must be comparable.

func ContainsWithPredicate

func ContainsWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) bool

ContainsWithPredicate checks if a slice contains an item. Use predicate to compare items.

func Difference

func Difference[T comparable](slice, other []T) []T

Difference returns a new slice containing all items from slice that are not present in other.

func Filter

func Filter[T any](slice []T, predicate func(T) bool) []T

Filter returns a new slice containing all items from slice for which predicate returns true.

func FilterNot

func FilterNot[T any](slice []T, predicate func(T) bool) []T

FilterNot returns a new slice containing all items from slice for which predicate returns false.

func IndexOf

func IndexOf[T comparable](slice []T, item T) int

IndexOf returns the index of the first instance of item in slice, or -1 if item is not present in slice.

func IndexOfWithPredicate

func IndexOfWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) int

IndexOfWithPredicate returns the index of the first instance of item in slice, or -1 if item is not present in slice. Use predicate to compare items.

func Intersection

func Intersection[T comparable](slice, other []T) []T

Intersection returns a new slice containing all items from slice that are also present in other.

func IsZero

func IsZero(t any) bool

IsZero returns true if the given value is the zero value for its type.

func LastIndexOf

func LastIndexOf[T comparable](slice []T, item T) int

LastIndexOf returns the index of the last instance of item in slice, or -1 if item is not present in slice.

func LastIndexOfWithPredicate

func LastIndexOfWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) int

LastIndexOfWithPredicate returns the index of the last instance of item in slice, or -1 if item is not present in slice. Use predicate to compare items.

func LoadPropFile

func LoadPropFile[T any](filePath string, props []T) error

LoadPropFile loads configuration properties from a file into the provided slice of structs. The file format can be either YAML or JSON. The 'filePath' parameter specifies the path to the configuration file. The 'props' parameter is a slice of pointers to struct instances that should be populated with the loaded properties. Returns an error if the file cannot be loaded, parsed, or is of an unsupported format.

func Map

func Map[T, R any](slice []T, mapper func(T) R) []R

Map returns a new slice containing the results of applying the given mapper function to each item in slice.

func Remove

func Remove[T comparable](slice []T, item T) bool

Remove removes the first instance of item from slice, if present. Returns true if item was removed, false otherwise.

func RemoveAll

func RemoveAll[T comparable](slice []T, item T) bool

RemoveAll removes all instances of item from slice, if present. Returns true if item was removed, false otherwise.

func RemoveAllWithPredicate

func RemoveAllWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) bool

RemoveAllWithPredicate removes all instances of item from slice, if present. Use predicate to compare items. Returns true if item was removed, false otherwise.

func RemoveAt

func RemoveAt[T any](slice []T, index int) bool

RemoveAt removes the item at the given index from slice. Returns true if item was removed, false otherwise.

func RemoveDuplicates

func RemoveDuplicates[T comparable](slice []T) bool

RemoveDuplicates removes all duplicate items from slice. Returns true if items were removed, false otherwise.

func RemoveIf

func RemoveIf[T any](slice []T, predicate func(T) bool) bool

RemoveIf removes all items from slice for which predicate returns true. Returns true if items were removed, false otherwise.

func RemoveRange

func RemoveRange[T any](slice []T, start, end int) bool

RemoveRange removes the items in the given range from slice. Returns true if items were removed, false otherwise.

func RemoveWithPredicate

func RemoveWithPredicate[T any](slice []T, item T, predicate func(T, T) bool) bool

RemoveWithPredicate removes the first instance of item from slice, if present. Use predicate to compare items. Returns true if item was removed, false otherwise.

func Reverse

func Reverse[T any](slice []T)

Reverse reverses the order of items in slice.

func ToPtr

func ToPtr[T any](t T) *T

ToPtr returns a pointer to the given value.

func Union

func Union[T comparable](slice, other []T) []T

Union returns a new slice containing all items from slice and other.

Types

type ConcurrentExec

type ConcurrentExec struct {
	// contains filtered or unexported fields
}

ConcurrentExec allows to execute a slice of ConcurrentFn concurrently. The running state, results, errors and context for the concurrent execution are stored within the struct.

func (*ConcurrentExec) CancelExecution

func (ce *ConcurrentExec) CancelExecution()

func (*ConcurrentExec) Done

func (ce *ConcurrentExec) Done() <-chan struct{}

func (*ConcurrentExec) Errors

func (ce *ConcurrentExec) Errors() []error

func (*ConcurrentExec) ExecuteFns

func (ce *ConcurrentExec) ExecuteFns(ctx context.Context, fns ...ConcurrentFn) (ConcurrentExecResponse, error)

ExecuteFns receives a context and a slice of functions to execute concurrently. It returns a ConcurrentExecResponse interface and an error if execution could not be started.

func (*ConcurrentExec) Results

func (ce *ConcurrentExec) Results() []any

type ConcurrentExecResponse

type ConcurrentExecResponse interface {
	// Results blocks until all functions are done and returns the results.
	Results() []any // blocks until all fns are done

	// Errors blocks until all functions are done and returns any errors that occurred.
	Errors() []error // blocks until all fns are done

	// CancelExecution cancels the execution of all functions.
	CancelExecution() // cancels the execution of all fns

	// Done returns a channel that is closed when all functions are done.
	Done() <-chan struct{} // returns a channel that is closed when all fns are done
}

ConcurrentExecResponse is the interface returned by ExecuteFns to interact with the results of the concurrent execution.

type ConcurrentFn

type ConcurrentFn func(ctx context.Context) (any, error)

ConcurrentFn represents a function that can be executed concurrently. The function receives a context and returns a result and an error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL