Documentation
¶
Overview ¶
Package util provides utility functions and types for common operations.
This file contains simple helpers for computing arithmetic means: a running average over all observed values (Average) and a smoothed moving average (MovingAverage). These types are lightweight and not concurrency-safe; if you need to use them from multiple goroutines, add your own synchronization.
Package util provides utility functions and types for common operations.
Package util provides utility functions and types for common operations.
Package util provides utility functions and types for common operations.
Package util provides utility functions and types for common operations.
Package util provides utility functions and types for common operations.
Package util contains small helper types and functions shared across the project.
This file provides a generic, concurrency-safe RandomQueue that allows adding items and retrieving/removing a random item in O(1) time on average using a swap-with-last pop technique.
Package util provides utility functions and types for common operations.
Package util provides utility functions and types for common operations.
Package util provides utility functions and types for common operations.
Package util provides utility functions and types for common operations.
Index ¶
- Variables
- func AlmostEqual[T ~float64 | ~float32](a, b T) bool
- func Count[T any](d []T, f func(ele T) bool) int64
- func IsASCIIDigits(s string) bool
- type Average
- type Debouncer
- type EmailRelay
- type MovingAverage
- type PubSub
- type PubSubDebouncer
- type RandomQueue
- type Signed
- type TimeSeries
- type TrackedValue
- type Uint64FromString
- type UnixTimeFromInt
- type UnixTimeFromIntString
- type ValueIF
- type Vector2D
- func (v *Vector2D[T]) Add(other *Vector2D[T]) *Vector2D[T]
- func (v *Vector2D[T]) Copy() *Vector2D[T]
- func (v *Vector2D[T]) Magnitude() float64
- func (v *Vector2D[T]) NormalizeToUnit() *Vector2D[T]
- func (v *Vector2D[T]) Rotate(theta float64) *Vector2D[T]
- func (v *Vector2D[T]) Scale(factor float64) *Vector2D[T]
- func (v *Vector2D[T]) ScaleToMaxComponent() *Vector2D[T]
- func (v *Vector2D[T]) ScaleXY(factorX, factorY float64) *Vector2D[T]
- func (v *Vector2D[T]) String() string
- func (v *Vector2D[T]) ThetaDegrees() float64
- func (v *Vector2D[T]) ThetaRadians() float64
- func (v *Vector2D[T]) Translate(dx, dy T) *Vector2D[T]
- func (v *Vector2D[T]) X() T
- func (v *Vector2D[T]) Y() T
- type WorkerPool
Constants ¶
This section is empty.
Variables ¶
var ( // DollarsFormat formats numbers as dollars with 2 decimal places (e.g., $123.45) DollarsFormat = accounting.Accounting{Symbol: "$", Precision: 2} // CentsFormat formats numbers as cents with 2 decimal places (e.g., ¢123.45) CentsFormat = accounting.Accounting{Symbol: "¢", Precision: 2} // DollarsCentsFormat formats numbers as dollars with 4 decimal places for precise values (e.g., $123.4567) DollarsCentsFormat = accounting.Accounting{Symbol: "$", Precision: 4} // DollarsCentsFormat2 formats numbers as dollars with 2 decimal places (same as DollarsFormat) DollarsCentsFormat2 = accounting.Accounting{Symbol: "$", Precision: 2} // PercentFormat formats numbers as percentages with 2 decimal places (e.g., 12.34%) PercentFormat = accounting.Accounting{Symbol: "%", Precision: 2} // NumberFormat formats numbers with thousands separators and no decimal places (e.g., 1,234,567) NumberFormat = accounting.Accounting{Symbol: "", Precision: 0, Thousand: ",", Decimal: ".", Format: "", FormatNegative: "", FormatZero: ""} )
Pre-configured accounting formatters for various currency and number formats. These can be used directly to format numbers in different display styles.
Functions ¶
func AlmostEqual ¶ added in v1.0.2
AlmostEqual compares two floating-point numbers and determines if they are approximately equal. It uses a fixed epsilon value of 1e-6 for the comparison, which is suitable for most general-purpose floating-point comparisons where absolute precision is not required.
Parameters:
- a, b: The two floating-point values to compare (can be either float32 or float64)
Returns:
- true if the absolute difference between a and b is less than 1e-6
- false otherwise
func Count ¶
Count counts the elements in the slice `d` satisfying the predicate function `f` and returns the count as int64.
func IsASCIIDigits ¶ added in v1.0.2
IsASCIIDigits returns true if s is non-empty and every rune is an ASCII digit ('0'..'9').
Types ¶
type Average ¶ added in v1.0.2
type Average struct {
// contains filtered or unexported fields
}
Average represents a simple arithmetic mean calculator over an entire set of values. It maintains a running sum (stored in the field "last") and a count of observed values to compute the mean on demand.
Zero value and initialization:
- The zero value of Average is not ready for use. Calling Get() on a zero value will cause a division-by-zero panic because count is 0.
- Use NewAverage(initial) to construct a valid instance or call Reset(initial) before the first use.
Concurrency: Average is not safe for concurrent use by multiple goroutines.
Note: The field name "last" actually stores the running sum of all values seen so far, not the last sample value.
func NewAverage ¶ added in v1.0.2
NewAverage returns a new Average initialized with the provided first value.
Parameters:
- initial: The first value to include in the average.
Returns: A pointer to a new Average instance initialized with the given value.
func (*Average) Get ¶ added in v1.0.2
Get returns the current arithmetic mean of all values observed so far.
Edge cases:
- If the Average was not initialized via NewAverage or Reset, and count is 0, this will panic due to division by zero.
func (*Average) Reset ¶ added in v1.0.2
Reset discards all previously accumulated values and initializes the average with the supplied initial value.
Parameters:
- initial: The new initial value to set for the average.
type Debouncer ¶ added in v1.0.2
type Debouncer[T any] struct { // contains filtered or unexported fields }
Debouncer is a generic struct that caches a value with a delay to prevent excessive recomputation or fetching. It uses a fetcher function to retrieve the value and a timeout to manage the validity of the cached value.
func NewDebouncer ¶ added in v1.0.2
NewDebouncer creates a new Debouncer with a specified delay and a fetcher function to retrieve values.
Parameters:
- delay: The duration to wait before allowing a new value to be fetched
- fetcher: A function that returns a value of type T and an error
Returns:
- A pointer to a new Debouncer instance
func (*Debouncer[T]) GetValue ¶ added in v1.0.2
GetValue retrieves the cached value or fetches a new one if the timeout has expired, updating the cache and timeout. If the timeout has expired, it calls the fetcher function to get a new value, updates the cache, and resets the timeout.
Returns:
- The cached value of type T
- An error if one occurred during fetching (nil if using cached value)
type EmailRelay ¶ added in v1.0.2
type EmailRelay struct {
// contains filtered or unexported fields
}
EmailRelay provides a simple interface for sending emails through an SMTP relay server. It handles the connection to the SMTP server and the email sending process.
func NewEmailRelay ¶ added in v1.0.2
func NewEmailRelay(relayHost string) *EmailRelay
NewEmailRelay creates a new EmailRelay instance with the specified SMTP relay host.
Parameters:
- relayHost: The hostname of the SMTP relay server (without port)
Returns:
- A pointer to a new EmailRelay instance
func (*EmailRelay) Send ¶ added in v1.0.2
func (r *EmailRelay) Send(from, to, body string) error
Send sends an email through the configured SMTP relay server. It establishes a connection to the server, sets the sender and recipient, sends the email body, and properly closes the connection.
Parameters:
- from: The email address of the sender
- to: The email address of the recipient
- body: The full email body, including headers and content
Returns:
- An error if any step of the email sending process fails, nil otherwise
type MovingAverage ¶ added in v1.0.2
type MovingAverage struct {
// contains filtered or unexported fields
}
MovingAverage maintains state for a smoothed moving average.
Semantics:
- NewMovingAverage(n, initial) configures smoothing based on n: larger n produces a slower, more stable response; smaller n reacts faster to new samples. The update rule applies a fraction of the delta between the new value and the current value. While not a textbook EMA, it provides a simple, stable smoothing behavior for many use cases.
Concurrency: MovingAverage is not safe for concurrent use by multiple goroutines.
func NewMovingAverage ¶ added in v1.0.2
func NewMovingAverage(n uint, initial float64) *MovingAverage
NewMovingAverage returns a MovingAverage configured with a smoothing window parameter n and an initial value. 'n' represents an intended window size: a higher 'n' yields a more stable (less volatile) output.
Panics if n <= 0.
func (*MovingAverage) Get ¶ added in v1.0.2
func (m *MovingAverage) Get() float64
Get returns the current moving average value.
func (*MovingAverage) Reset ¶ added in v1.0.2
func (m *MovingAverage) Reset(initial float64)
Reset sets the moving average back to the provided initial value without changing the smoothing configuration.
func (*MovingAverage) Update ¶ added in v1.0.2
func (m *MovingAverage) Update(v float64)
Update incorporates another data point into the moving average. The internal smoothing factor is derived from n passed to NewMovingAverage.
func (*MovingAverage) UpdateAndGet ¶ added in v1.0.2
func (m *MovingAverage) UpdateAndGet(v float64) float64
UpdateAndGet adds a new data point and returns the current moving average in one call.
type PubSub ¶ added in v1.0.2
func NewPubSub ¶ added in v1.0.2
NewPubSub creates a new instance of the PubSub struct with the specified type.
func (*PubSub[T]) Broadcast ¶ added in v1.0.2
func (s *PubSub[T]) Broadcast(msg T)
Broadcast sends a message to all registered channels in the PubSub. It acquires a read-lock to prevent changes to the clients slice during the snapshot. The clients slice is copied into a new buffer for non-concurrent iteration, then the lock is released. Sends the message to each channel in the buffer. Note: send may block if a channel has insufficient buffer or no receiver.
func (*PubSub[T]) IsActive ¶ added in v1.0.2
IsActive returns true if there are active clients subscribed to the PubSub object, otherwise false.
func (*PubSub[T]) Register ¶ added in v1.0.2
Register registers a new reception channel of size buffSize. If buffSize == 0 then broadcasting to this channel is synchronous.
func (*PubSub[T]) Size ¶ added in v1.0.2
Size returns the number of registered reception channels in the PubSub struct.
func (*PubSub[T]) Unregister ¶ added in v1.0.2
func (s *PubSub[T]) Unregister(c <-chan T)
Unregister removes the given reception channel from the PubSub. It removes it from the list of clients. If the channel is not found, nothing happens. The channel is not closed by PubSub to avoid races with concurrent senders.
type PubSubDebouncer ¶ added in v1.0.2
type PubSubDebouncer[T comparable] struct { sync.RWMutex // contains filtered or unexported fields }
PubSubDebouncer is a utility for debouncing values with a pub-sub mechanism for notifying listeners. It holds the latest value and enforces a delay duration before updates are allowed. Values are fetched using a provided fetcher function, and a context is used for cancellation. It uses a PubSub instance to broadcast updates to registered listeners.
func NewPubSubDebouncer ¶ added in v1.0.2
func NewPubSubDebouncer[T comparable](delay time.Duration, fetcher func() (T, error)) (*PubSubDebouncer[T], context.CancelFunc)
NewPubSubDebouncer creates a new PubSubDebouncer with a specified debounce delay and value-fetching function. Returns a pointer to the PubSubDebouncer and a context.CancelFunc for managing its lifecycle. The cancel function should be called when the debouncer is no longer needed to clean up resources.
Parameters:
- delay: The minimum duration between value updates (must be >= 100ms)
- fetcher: A function that returns a value of type T and an error
Returns:
- A pointer to a new PubSubDebouncer instance
- A context.CancelFunc that should be called to stop the debouncer when no longer needed
Panics:
- If the delay is less than 100 milliseconds
func (*PubSubDebouncer[T]) GetValue ¶ added in v1.0.2
func (d *PubSubDebouncer[T]) GetValue() (T, error)
GetValue retrieves the current value, refreshing it using the fetcher function if the timeout has expired. This method is thread-safe and uses a read lock to protect access to the debouncer's state.
Returns:
- The current value of type T (either cached or freshly fetched)
- An error if one occurred during fetching (nil if using cached value or if fetch was successful)
func (*PubSubDebouncer[T]) GetValueMust ¶ added in v1.0.2
func (d *PubSubDebouncer[T]) GetValueMust() T
GetValueMust retrieves the latest value from the debouncer and panics if an error occurs during fetching. This is a convenience method for cases where errors are not expected or should cause program termination.
Returns:
- The current value of type T
Panics:
- If an error occurs during value fetching
func (*PubSubDebouncer[T]) Register ¶ added in v1.0.2
func (d *PubSubDebouncer[T]) Register() <-chan T
Register registers a new listener channel for receiving debounced values. Starts the fetcher if no listeners are active. This method automatically starts the background fetcher goroutine if this is the first active listener.
Returns:
- A receive-only channel that will receive updates when the debounced value changes
func (*PubSubDebouncer[T]) SetValue ¶ added in v1.0.2
func (d *PubSubDebouncer[T]) SetValue(value T)
SetValue updates the stored value if it differs from the previous value, considering type-specific precision thresholds. Triggers a broadcast to notify listeners if the value changes and adjusts the timeout duration. For floating-point types (float32, float64), it uses a small epsilon value to determine if the value has changed. For other types, it uses direct equality comparison.
Parameters:
- value: The new value to store and potentially broadcast to listeners
func (*PubSubDebouncer[T]) Unregister ¶ added in v1.0.2
func (d *PubSubDebouncer[T]) Unregister(c <-chan T)
Unregister removes a specified listener channel from the debouncer's PubSub, closing the channel and freeing resources. If this was the last active listener, the background fetcher goroutine will automatically stop on its next iteration.
Parameters:
- c: The channel previously returned by Register() that should be unregistered
type RandomQueue ¶ added in v1.0.2
type RandomQueue[T any] struct { // contains filtered or unexported fields }
RandomQueue is a generic, mutex-protected container that stores items and returns a uniformly random element upon removal.
Concurrency:
- All exported methods acquire an internal mutex; callers can safely use the same queue from multiple goroutines.
Performance:
- GetAndRemove removes a random element in amortized O(1) time by swapping the chosen element with the last element, then shrinking the slice.
Zero value:
- The zero value of RandomQueue is not ready for use because the mutex is a pointer. Use NewRandomQueue to construct a working instance.
Edge cases:
- Calling GetAndRemove on an empty queue will panic due to rand.Intn(0). Call Len() first if emptiness is possible.
Example:
q := util.NewRandomQueue[int]() q.Add(1); q.Add(2); q.Add(3) x := q.GetAndRemove() // x is 1, 2, or 3 with equal probability n := q.Len() // remaining item count
T can be any type.
func NewRandomQueue ¶ added in v1.0.2
func NewRandomQueue[T any]() *RandomQueue[T]
NewRandomQueue constructs a new, ready-to-use RandomQueue.
func (*RandomQueue[T]) Add ¶ added in v1.0.2
func (r *RandomQueue[T]) Add(f T)
Add inserts a single item into the queue.
func (*RandomQueue[T]) GetAndRemove ¶ added in v1.0.2
func (r *RandomQueue[T]) GetAndRemove() T
GetAndRemove selects a uniformly random item from the queue, removes it, and returns it.
Note: This will panic if the queue is empty. Use Len() to guard if needed.
func (*RandomQueue[T]) Len ¶ added in v1.0.2
func (r *RandomQueue[T]) Len() int
Len returns the number of items currently stored in the queue.
type Signed ¶ added in v1.0.2
Signed is a constraint interface that allows for numeric types that can be used in vector calculations. This includes integers and floating point numbers.
type TimeSeries ¶ added in v1.0.2
type TimeSeries[T any] struct { PrecisionMask time.Duration // contains filtered or unexported fields }
TimeSeries represents a collection of time-stamped entries, indexed with specified time precision. PrecisionMask defines the time granularity used to group entries. The data field stores the actual time series as a map of time.Time to values of type *T.
func NewTimeSeriesMap ¶ added in v1.0.2
func NewTimeSeriesMap[T any](precision time.Duration) *TimeSeries[T]
NewTimeSeriesMap initializes and returns a new TimeSeries instance with the specified time precision. This implementation is NOT concurrent safe.
func (*TimeSeries[T]) Clear ¶ added in v1.0.2
func (ts *TimeSeries[T]) Clear()
Clear removes all entries from the TimeSeries, resetting its data storage to an empty state.
func (*TimeSeries[T]) Get ¶ added in v1.0.2
func (ts *TimeSeries[T]) Get(t time.Time) *T
Get retrieves the value associated with a specific time, truncated to the series' precision. Returns nil if not found.
func (*TimeSeries[T]) Keys ¶ added in v1.0.2
func (ts *TimeSeries[T]) Keys() []time.Time
Keys returns a sorted slice of all keys present in the TimeSeries.
func (*TimeSeries[T]) Len ¶ added in v1.0.2
func (ts *TimeSeries[T]) Len() int
Len returns the number of entries in the TimeSeries.
func (*TimeSeries[T]) Update ¶ added in v1.0.2
func (ts *TimeSeries[T]) Update(t time.Time, init func() *T, update func(*T))
Update adds or updates an entry in the time series for the specified time. If the time entry does not exist, it is created using the init function. If the time entry exists, it is modified using the update function.
type TrackedValue ¶ added in v1.0.2
type TrackedValue[T constraints.Float] struct { // contains filtered or unexported fields }
TrackedValue represents a value that can be tracked and updated.
func NewTrackedValue ¶ added in v1.0.2
func NewTrackedValue[T constraints.Float](v T, isCurrency bool, window uint) *TrackedValue[T]
NewTrackedValue initializes a new TrackedValue with the given parameters. The TrackedValue tracks the value and calculates a string representation including a trending symbol. The calculation of value is based on a moving average. The trend indicator is adjusted based on the last update value compared to the average.
Parameters:
- v: the initial value of the TrackedValue
- isCurrency: determines whether the TrackedValue represents a currency or not
- window: specifies the number of values to consider when calculating the moving average
Returns:
- *TrackedValue[T]: a pointer to the newly created TrackedValue instance
func (*TrackedValue[T]) String ¶ added in v1.0.2
func (t *TrackedValue[T]) String() string
String returns the string representation of the TrackedValue. It retrieves the pre-calculated stringValue field. Returns:
- string: the string representation of the TrackedValue.
func (*TrackedValue[T]) Update ¶ added in v1.0.2
func (t *TrackedValue[T]) Update(v T) (changed bool)
Update updates the TrackedValue. It calculates the average value, compares it to the new value, and updates the symbol accordingly. Finally, it calculates a new string representation based on the value and symbol. If the string representation changes, the returned value is true, else false.
Parameters: - v: the new value to update the TrackedValue with
Returns: - changed: a boolean indicating if the value has changed compared to the previous value
func (*TrackedValue[T]) Value ¶ added in v1.0.2
func (t *TrackedValue[T]) Value() T
Value returns the current value stored in the TrackedValue. It retrieves the value field. Returns:
- T: the current value stored in the TrackedValue.
type Uint64FromString ¶ added in v1.0.2
type Uint64FromString uint64
Uint64FromString is a custom type for unmarshaling JSON string values containing unsigned 64-bit integers into Go uint64 values. It implements the json.Unmarshaler interface.
func (*Uint64FromString) UnmarshalJSON ¶ added in v1.0.2
func (ut *Uint64FromString) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for Uint64FromString. It parses a JSON string containing a numeric value and converts it to a uint64.
Parameters:
- data: The JSON data to unmarshal
Returns:
- An error if unmarshaling or parsing fails, nil otherwise
func (*Uint64FromString) Value ¶ added in v1.0.2
func (ut *Uint64FromString) Value() uint64
Value returns the underlying uint64 value from the Uint64FromString.
Returns:
- The uint64 value represented by this Uint64FromString
type UnixTimeFromInt ¶ added in v1.0.2
UnixTimeFromInt is a custom type for unmarshaling JSON numeric values containing Unix timestamps into Go time.Time objects. It implements the json.Unmarshaler interface.
func (*UnixTimeFromInt) UnmarshalJSON ¶ added in v1.0.2
func (ut *UnixTimeFromInt) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for UnixTimeFromInt. It parses a JSON number containing a Unix timestamp (seconds since epoch) and converts it to a time.Time.
Parameters:
- data: The JSON data to unmarshal
Returns:
- An error if unmarshaling fails, nil otherwise
func (*UnixTimeFromInt) Value ¶ added in v1.0.2
func (ut *UnixTimeFromInt) Value() time.Time
Value returns the underlying time.Time value from the UnixTimeFromInt.
Returns:
- The time.Time value represented by this UnixTimeFromInt
type UnixTimeFromIntString ¶ added in v1.0.2
UnixTimeFromIntString is a custom type for unmarshaling JSON string values containing Unix timestamps into Go time.Time objects. It implements the json.Unmarshaler interface.
func (*UnixTimeFromIntString) UnmarshalJSON ¶ added in v1.0.2
func (ut *UnixTimeFromIntString) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for UnixTimeFromIntString. It parses a JSON string containing a Unix timestamp (seconds since epoch) and converts it to a time.Time.
Parameters:
- data: The JSON data to unmarshal
Returns:
- An error if unmarshaling or parsing fails, nil otherwise
func (*UnixTimeFromIntString) Value ¶ added in v1.0.2
func (ut *UnixTimeFromIntString) Value() time.Time
Value returns the underlying time.Time value from the UnixTimeFromIntString.
Returns:
- The time.Time value represented by this UnixTimeFromIntString
type ValueIF ¶ added in v1.0.2
type ValueIF[T constraints.Float] interface { fmt.Stringer Update(v T) bool Value() T }
ValueIF is an interface that represents a value which can be tracked and updated. It extends `fmt.Stringer` interface and requires implementations to have the following methods: - Update(v T) bool: updates the value with the provided value `v`, returns `true` if the update was successful. - Value() T: retrieves the current value of the object.
type Vector2D ¶ added in v1.0.2
type Vector2D[T Signed] struct { // contains filtered or unexported fields }
Vector2D represents a 2D vector with x and y components. It is a generic type that can work with any numeric type that satisfies the Signed interface.
func NewVector2D ¶ added in v1.0.2
NewVector2D creates and returns a new Vector2D with the specified x and y components. It uses generics to work with any numeric type that satisfies the Signed interface.
Parameters:
- dx: The x-component of the vector
- dy: The y-component of the vector
Returns:
- A pointer to a new Vector2D instance with the specified components
func (*Vector2D[T]) Add ¶ added in v1.0.2
Add updates this vector to be the sum of this vector and the other vector. The operation is performed component-wise, adding the dx and dy values separately. This method modifies the vector in place.
Parameters:
- other: The vector to add to this vector
Returns:
- A pointer to this vector after the addition operation, allowing for method chaining
func (*Vector2D[T]) Copy ¶ added in v1.0.2
Copy creates and returns a new Vector2D with the same component values as this vector. This method does not modify the original vector and returns a pointer to the new copy.
Returns:
- A pointer to a new Vector2D instance with the same component values as this vector
func (*Vector2D[T]) Magnitude ¶ added in v1.0.2
Magnitude computes and returns the length (magnitude) of the vector as a float64. It uses the Pythagorean theorem to calculate the distance from the origin.
Returns:
- The magnitude of the vector as a float64 value
func (*Vector2D[T]) NormalizeToUnit ¶ added in v1.0.2
NormalizeToUnit modifies this vector to have a magnitude (length) of 1.0 while preserving its direction. This is a true normalization that creates a unit vector. If the vector has zero magnitude, it remains unchanged to avoid division by zero.
Returns:
- A pointer to this vector after the normalization operation, allowing for method chaining
func (*Vector2D[T]) Rotate ¶ added in v1.0.2
Rotate rotates this vector counter-clockwise by the given angle in radians. The rotation is performed in place using the standard 2D rotation matrix:
x' = x*cos(theta) - y*sin(theta) y' = x*sin(theta) + y*cos(theta)
Parameters:
- theta: rotation angle in radians (positive is counter-clockwise)
Returns:
- A pointer to this vector after rotation, allowing method chaining
func (*Vector2D[T]) Scale ¶ added in v1.0.2
Scale multiplies both components of this vector by the given factor. This method modifies the vector in place, scaling its magnitude while preserving its direction (unless factor is negative).
Parameters:
- factor: The value to multiply both components by
Returns:
- A pointer to this vector after the scaling operation, allowing for method chaining
func (*Vector2D[T]) ScaleToMaxComponent ¶ added in v1.0.2
ScaleToMaxComponent modifies this vector so that the largest component becomes 1.0, and the other component is scaled proportionally. This is not a true normalization to unit length (see NormalizeToUnit for that), but rather a simplification of the vector's representation.
Returns:
- A pointer to this vector after the scaling operation, allowing for method chaining
func (*Vector2D[T]) ScaleXY ¶ added in v1.0.2
ScaleXY multiplies the x-component by factorX and the y-component by factorY. This method modifies the vector in place, allowing for non-uniform scaling that can change both the magnitude and direction of the vector.
Parameters:
- factorX: The value to multiply the x-component by
- factorY: The value to multiply the y-component by
Returns:
- A pointer to this vector after the scaling operation, allowing for method chaining
func (*Vector2D[T]) String ¶ added in v1.0.2
String returns a string representation of the vector in the format {dx, dy}. This method implements the fmt.Stringer interface, allowing the vector to be used directly with fmt.Print functions.
Returns:
- A string representation of the vector with components formatted to 4 significant digits
func (*Vector2D[T]) ThetaDegrees ¶ added in v1.0.2
ThetaDegrees returns the angle this vector represents in degrees. Angle 0 is on the positive x-axis (horizontal line) and increases counter-clockwise around to 360 degrees. This is a convenience method that converts the result of ThetaRadians to degrees.
Returns:
- The angle of the vector in degrees (range 0 to 360)
func (*Vector2D[T]) ThetaRadians ¶ added in v1.0.2
ThetaRadians returns the angle this vector represents in radians. Angle 0 is on the positive x-axis (horizontal line) and increases counter-clockwise around to 2*PI. Negative angles are converted to their positive equivalent.
Returns:
- The angle of the vector in radians (range 0 to 2*PI)
func (*Vector2D[T]) Translate ¶ added in v1.0.2
Translate moves this vector by adding the specified dx and dy values to its components. This method modifies the vector in place.
Parameters:
- dx: The amount to add to the x-component
- dy: The amount to add to the y-component
Returns:
- A pointer to this vector after the translation operation, allowing for method chaining
type WorkerPool ¶ added in v1.0.2
WorkerPool is a generic worker pool that processes work items concurrently and stores results. It uses channels to dispatch work, collect results, and retains a function to process each work item.
func NewWorkerPool ¶ added in v1.0.2
func NewWorkerPool[W any, R any](f func(W) R, backlog int, numWorkers int) *WorkerPool[W, R]
NewWorkerPool creates and initializes a new WorkerPool with the given worker function, backlog size, and number of workers. It panics if backlog is negative or numWorkers is less than 1.
func (*WorkerPool[W, R]) Close ¶ added in v1.0.2
func (wp *WorkerPool[W, R]) Close()
Close terminates the work channel, signaling that no more work items will be submitted to the WorkerPool.
func (*WorkerPool[W, R]) IsActive ¶ added in v1.0.2
func (wp *WorkerPool[W, R]) IsActive() bool
IsActive checks if the WorkerPool has active work items by verifying if the active work count is greater than zero.
func (*WorkerPool[W, R]) Len ¶ added in v1.0.2
func (wp *WorkerPool[W, R]) Len() int32
Len returns the current number of active work items in the WorkerPool.
func (*WorkerPool[W, R]) Post ¶ added in v1.0.2
func (wp *WorkerPool[W, R]) Post(w W)
Post submits a work item to the WorkerPool for processing and increments the active work count. This will block when the channel is full.
func (*WorkerPool[W, R]) Result ¶ added in v1.0.2
func (wp *WorkerPool[W, R]) Result() R
Result retrieves and returns the next available result from the worker pool, decrementing the active work count.