q

package module
v0.11.3 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2025 License: MIT Imports: 10 Imported by: 7

README

q 🚀

Helper functions galore!

Getting Started

To integrate Project Q with your project, include it in your go.mod file or execute:

go get github.com/patrixr/q

Testing

To run the tests, execute the following command in the project root directory:

go test ./...

Contributing

We welcome contributions to Project Q! If you'd like to contribute, please fork the repository and use a feature branch. Pull requests are welcome.

License

Project Q is distributed under the MIT license. By contributing to Project Q, you agree that your contributions will be licensed under its MIT license.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Assert added in v0.10.2

func Assert(truth bool, msg string)

func AssertNil added in v0.10.2

func AssertNil(item any, msg string)

func AssertNoError added in v0.10.2

func AssertNoError(err error)

func AssertNotNil added in v0.10.2

func AssertNotNil(item any, msg string)

func Boom added in v0.10.2

func Boom(msg string)

func Ellipsis

func Ellipsis(s string, max int) string

Ellipsis truncates a string to a maximum length and appends an ellipsis ("...") if the original string exceeds the maximum length. If the string is shorter than or equal to the maximum length, it returns the original string without modification.

Parameters:

  • s: The original string to be truncated.
  • max: The maximum allowed length of the string.

Returns:

A string that is either the original string (if its length is less than
or equal to max) or a truncated version of the original string with an
ellipsis appended (if its length is greater than max).

func Eq added in v0.6.2

func Eq[T comparable](val T) func(T, int) bool

Eq returns a predicate function that checks if an element is equal to the specified value.

Parameters:

  • val: The value to compare each element against.

Returns:

  • func(T, int) bool: A predicate function that takes an element of type T and its index, and returns true if the element is equal to val, otherwise false.

Example usage with Find:

array := []int{1, 2, 3, 4, 5}
found, element, index := q.Find(array, q.Eq(3))
// found: true, element: 3, index: 2

func Filter

func Filter[T any](a []T, f func(T) bool) []T

Filter returns a new slice containing all elements of a for which the function f returns true. It iterates over each element of the input slice, applying the function f to it. If f returns true, the element is included in the resulting slice. The order of elements in the input slice is preserved in the output slice.

This function is generic and can operate on slices of any type, as indicated by the type parameter T. The function f takes a single argument of the same type as the elements of the slice and returns a bool.

Parameters:

a []T: The input slice containing elements of any type T.
f func(T) bool: A function that takes an element of type T and returns a bool. Elements for which f returns
true are included in the resulting slice.

Returns:

[]T: A new slice containing all elements of the input slice for which the function f returns true.

Example:

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

func Find added in v0.6.0

func Find[T any](array []T, predicate func(T, int) bool) (bool, T, int)

Find searches for an element in the array that satisfies the predicate function. It returns a boolean indicating whether such an element was found, the element itself, and the index of the element in the array. If no element is found, it returns false, the zero value of the element type, and -1.

The function is generic and works with any type T that is comparable.

Parameters:

  • array: A slice of elements of type T to search through.
  • predicate: A function that takes an element of type T and its index, and returns a boolean indicating whether the element satisfies the condition.

Returns: - bool: True if an element satisfying the predicate is found, otherwise false. - T: The element that satisfies the predicate, or the zero value of type T if not found. - int: The index of the element in the array, or -1 if not found.

func FindAll added in v0.9.0

func FindAll[T any](array []T, predicate func(T, int) bool) []T

FindAll searches for all elements in the array that satisfy the predicate function. It returns a slice of elements that satisfy the predicate.

The function is generic and works with any type T.

Parameters:

  • array: A slice of elements of type T to search through.
  • predicate: A function that takes an element of type T and its index, and returns a boolean indicating whether the element satisfies the condition.

Returns: - []T: A slice of elements that satisfy the predicate. If no elements are found, it returns an empty slice.

Example usage:

array := []int{1, 2, 3, 4, 5}
results := q.FindAll(array, func(n int, _ int) bool { return n%2 == 0 })
// results: []int{2, 4}

func Last added in v0.2.0

func Last[E any](s []E) (E, bool)

Last returns the last element of a slice and a boolean indicating if the slice was non-empty. If the slice is empty, it returns the zero value of the element type and false.

func Map

func Map[T any, M any](a []T, f func(T) M) []M

Map applies a function to each element of a slice, returning a new slice of the results. The function f is applied to each element of the input slice a, and a new slice of the resulting type M is returned. This allows for transforming slices of one type into slices of another type through the provided function.

Parameters: a - The input slice of type []T. f - The function to apply to each element of a. The function must take a value of type T and return a value of type M.

Returns: A new slice of type []M containing the results of applying f to each element of a.

func Match added in v0.7.2

func Match(rexp string) func(string, int) bool

Match returns a predicate function that checks if an element matches the specified regular expression. The function returns true if the element matches the regular expression, otherwise false.

func Paragraph added in v0.7.1

func Paragraph(text string) string

Alias for TrimIndent

func ReadEnv

func ReadEnv(key string, defaultValue string) string

ReadEnv retrieves the value of the environment variable named by the key. If the environment variable is not set, or is empty, the defaultValue is returned.

func ReadEnvBool

func ReadEnvBool(key string, defaultValue bool) bool

ReadEnvBool retrieves the boolean value of the environment variable named by the key. If the environment variable is not set, or is empty, or cannot be converted to a boolean, the defaultValue is returned.

func ReadEnvBoolStrict

func ReadEnvBoolStrict(key string) bool

ReadEnvBoolStrict retrieves the boolean value of the environment variable named by the key. It panics if the environment variable is not set, is empty, or cannot be converted to a boolean.

func ReadEnvInt

func ReadEnvInt(key string, defaultValue int) int

ReadEnvInt retrieves the integer value of the environment variable named by the key. If the environment variable is not set, or is empty, or cannot be converted to an integer, the defaultValue is returned.

func ReadEnvIntStrict

func ReadEnvIntStrict(key string) int

ReadEnvIntStrict retrieves the integer value of the environment variable named by the key. It panics if the environment variable is not set, is empty, or cannot be converted to an integer.

func ReadEnvStrict

func ReadEnvStrict(key string) string

ReadEnvStrict retrieves the value of the environment variable named by the key. It panics if the environment variable is not set or is empty.

func TrimIndent added in v0.7.1

func TrimIndent(s string) string

TrimIndent removes the common leading whitespace from each line in a given string. It first determines the minimum indentation level across all non-empty lines, then removes that amount of leading whitespace from each line and trims any additional leading or trailing whitespace.

Parameters:

s (string): The input string with potential leading indentation.

Returns:

string: A new string with the common leading indentation removed from each line.

Example:

input := "    line1\n    line2\n    line3"
output := TrimIndent(input)
// output will be:
// "line1\nline2\nline3"

func Uniq

func Uniq[T comparable](inputSlice []T) []T

Uniq removes duplicates from a slice of any comparable type and returns a slice of unique elements. It preserves the order of the first occurrence of each element.

Parameters: - inputSlice: A slice of any comparable type (e.g., int, string) from which duplicates need to be removed.

Returns: A new slice containing only the unique elements from the input slice, in the order of their first occurrence.

Example:

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

Types

type BackgroundJob added in v0.3.0

type BackgroundJob[J any] struct {
	// contains filtered or unexported fields
}

func (*BackgroundJob[J]) Close added in v0.3.0

func (job *BackgroundJob[J]) Close()

func (*BackgroundJob[J]) PerformLater added in v0.3.0

func (job *BackgroundJob[J]) PerformLater(j J)

func (*BackgroundJob[J]) PerformNow added in v0.3.0

func (job *BackgroundJob[J]) PerformNow(j J) error

type Cache

type Cache[T any] interface {
	Set(key string, value T) error
	Get(key string) (T, bool)
	Invalidate(key string)
	Cleanup()
	Clear()
	Len() int
}

type EventEmitter added in v0.11.0

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

func (*EventEmitter) AddEventHandler added in v0.11.0

func (emitter *EventEmitter) AddEventHandler(ev string, fn EventHandler, multiple bool) EventRef

func (*EventEmitter) Fire added in v0.11.0

func (emitter *EventEmitter) Fire(ev string, data any) (bool, []error)

func (*EventEmitter) Off added in v0.11.0

func (emitter *EventEmitter) Off(ev string, ref EventRef)

func (*EventEmitter) On added in v0.11.0

func (emitter *EventEmitter) On(ev string, fn EventHandler) EventRef

func (*EventEmitter) Once added in v0.11.0

func (emitter *EventEmitter) Once(ev string, fn EventHandler) EventRef

type EventHandler added in v0.11.0

type EventHandler func(ev string, data any) error

type EventRef added in v0.11.0

type EventRef int

type Eventful added in v0.11.0

type Eventful interface {
	On(ev string, cb EventHandler) EventRef
	Once(ev string, cb EventHandler) EventRef
	Off(ev string, ref EventRef)
	Fire(ev string, data any) (bool, []error)
}

func NewEventEmitter added in v0.11.0

func NewEventEmitter(ctx context.Context, concurrency int) Eventful

type InMemoryCache

type InMemoryCache[T any] struct {
	// contains filtered or unexported fields
}

func NewInMemoryCache

func NewInMemoryCache[T any](ttl time.Duration) *InMemoryCache[T]

NewInMemoryCache creates a new instance of InMemoryCache with the specified time-to-live (TTL) for cache items. It initializes an empty cache with the given TTL value.

Parameters: - ttl: A time.Duration value that specifies the time-to-live for each cache item.

Returns: - A pointer to the newly created InMemoryCache instance.

func (*InMemoryCache[T]) Cleanup

func (c *InMemoryCache[T]) Cleanup()

func (*InMemoryCache[T]) Clear

func (c *InMemoryCache[T]) Clear()

func (*InMemoryCache[T]) Get

func (c *InMemoryCache[T]) Get(key string) (T, bool)

func (*InMemoryCache[T]) Invalidate

func (c *InMemoryCache[T]) Invalidate(key string)

func (*InMemoryCache[T]) Len

func (c *InMemoryCache[T]) Len() int

func (*InMemoryCache[T]) Set

func (c *InMemoryCache[T]) Set(key string, value T) error

type InMemoryCacheItem

type InMemoryCacheItem[T any] struct {
	Data      T
	Timestamp time.Time
}

type JobProcessor added in v0.3.0

type JobProcessor[T any] interface {
	PerformLater(T)
	PerformNow(T) error
	Close()
}

func NewBackgroundJob added in v0.3.0

func NewBackgroundJob[J any](
	ctx context.Context,
	executor func(J) error,
	errorHandler func(J, error),
	concurrency int,
) JobProcessor[J]

NewBackgroundJob creates a new background job processor with the given executor function, error handler, and concurrency. The executor function is called for each job in the queue. It uses Go routines to process the jobs concurrently.

type Node added in v0.8.0

type Node[T any] struct {
	Root     bool
	Data     T
	Children []*Node[T]
}

func Tree added in v0.8.0

func Tree[T any](val T) *Node[T]

func (*Node[T]) Add added in v0.8.0

func (tree *Node[T]) Add(child T) *Node[T]

func (*Node[T]) FindChild added in v0.8.1

func (tree *Node[T]) FindChild(predicate func(T) bool) *Node[T]

func (*Node[T]) Traverse added in v0.8.0

func (tree *Node[T]) Traverse(cb func(it T))

type Pair added in v0.9.2

type Pair[K any, V any] struct {
	Key   K
	Value V
}

func NewPair added in v0.9.2

func NewPair[K any, V any](key K, value V) Pair[K, V]

Jump to

Keyboard shortcuts

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