util

package module
v0.0.0-...-3e76bab Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2025 License: MIT Imports: 18 Imported by: 0

README

util

Go Test

A collection of reusable utility functions for Go, designed to simplify common tasks and enhance code clarity across projects.

Documentation

Index

Constants

View Source
const (
	HalfHour   = 30 * time.Minute
	HalfSecond = 500 * time.Millisecond
)

Variables

View Source
var ErrChClosed = errors.New("ch closed")

Functions

func Abs

func Abs[R constraints.Signed | constraints.Float](x R) R

Abs returns the absolute value of x. It supports generic Integer and Float types.

func AllBy

func AllBy[S ~[]V, K comparable, V any](s S, toKey func(v V) K) iter.Seq2[K, V]

func Ceil

func Ceil[I constraints.Integer, F constraints.Float](x F) I

Ceil returns the smallest integer value greater than or equal to x. It supports generic Integer and Float types.

Special cases are:

Ceil(±0) = ±0
Ceil(±Inf) = ±Inf
Ceil(NaN) = NaN

func Clock

func Clock(t time.Time) time.Duration

Clock returns the duration since the start of the day for the given time in its timezone, including sub-second precision.

For example:

Clock(2025-08-08 15:30:00.123 JST) = 15h30m0.123s

func Compare

func Compare[T Ordered](x, y T) int

Compare compares two Ordered values x and y. It returns -1 if x is less than y, 0 if x equals y, and +1 if x is greater than y. It handles various ordered types including bool.

func DayOfWeekInWeek

func DayOfWeekInWeek(t time.Time, startOfWeek time.Weekday) int

DayOfWeekInWeek returns the 0-indexed day of the week, where startOfWeek is 0.

For example:

DayOfWeekInWeek(2025-01-08 (Wednesday), Monday) = 2

func DaysBetween

func DaysBetween(from, to time.Time) int

DaysBetween returns the number of days between two time.Time values, ignoring time components and considering only dates. It calculates the number of days from 'from' to 'to'.

For example:

DaysBetween(2025-01-01, 2025-01-03) = 2
DaysBetween(2025-01-01, 2025-01-01) = 0
DaysBetween(2025-01-03, 2025-01-01) = -2

func DivMod

func DivMod[I constraints.Integer](n, d I) (q, r I)

DivMod returns the quotient (q) and remainder (r) of the division n/d. The division truncates toward zero, and the remainder has the same sign as the dividend (n). For example: DivMod(5, 3) returns (1, 2) DivMod(-5, 3) returns (-1, -2) DivMod(5, -3) returns (-1, 2) DivMod(-5, -3) returns (1, -2)

func ErrorAs

func ErrorAs[T error](err error) (asErr T, ok bool)

ErrorAs checks if an error in err's chain matches target, and if so, sets target to the matching error. It is a generic wrapper around errors.As.

func Filter

func Filter[T any](seq iter.Seq[T], predicate func(item T) bool) iter.Seq[T]

func Filter2

func Filter2[K, V any](seq iter.Seq2[K, V], predicate func(k K, v V) bool) iter.Seq2[K, V]

func FilterMapToSlice

func FilterMapToSlice[K comparable, V, R any, M ~map[K]V](in M, iteratee func(key K, value V) (R, bool)) []R

FilterMapToSlice filters and transforms map elements into a new slice. The iteratee function determines whether an element is included and how it's transformed.

func FindUp

func FindUp(file string) (path string, ok bool)

FindUp searches for a file by walking up parent directories from the current directory. If the file is found, it returns the absolute path and true. If the file is not found up to the root directory, it returns an empty string and false.

func Floor

func Floor[I constraints.Integer, F constraints.Float](x F) I

Floor returns the greatest integer value less than or equal to x. It supports generic Integer and Float types.

Special cases are:

Floor(±0) = ±0
Floor(±Inf) = ±Inf
Floor(NaN) = NaN

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a time.Duration into a string in HH:MM:SS.ms format. It handles negative durations and includes millisecond precision if present.

For example:

FormatDuration(1*time.Hour + 2*time.Minute + 3*time.Second + 456*time.Millisecond) = "01:02:03.456"
FormatDuration(-1*time.Minute) = "-00:01:00"

func Future

func Future(t time.Time) bool

Future reports whether t is after time.Now(). It is shorthand for t.After(time.Now()).

func GetTypeName

func GetTypeName[T any]() string

GetTypeName returns the name of the type T. If T is a pointer type, it returns the name with a leading asterisk (e.g., "*MyStruct").

func GetTypeNameFromValue

func GetTypeNameFromValue(value any) string

GetTypeNameFromValue returns the name of the type of the given value. If the value is a pointer, it returns the name with a leading asterisk (e.g., "*MyStruct"). It panics if value is nil.

func GetTypeString

func GetTypeString[T any]() string

GetTypeString returns the string representation of the type T. This includes the package path if the type is from another package.

func GetTypeStringFromValue deprecated

func GetTypeStringFromValue(value any) string

Deprecated: Use GetTypeNameFromValue instead, as GetTypeStringFromValue might return unexpected results for anonymous types or interfaces.

func IndexMap

func IndexMap[T comparable, S ~[]T](collection S) map[T]int

[]T -> map[T]index

func IsExist

func IsExist(file string) bool

IsExist checks if a file or directory exists.

func Map

func Map[T, R any](seq iter.Seq[T], iteratee func(item T) R) iter.Seq[R]

func Map1To2

func Map1To2[T, K, V any](seq iter.Seq[T], iteratee func(item T) (K, V)) iter.Seq2[K, V]

func Map2

func Map2[K1, V1, K2, V2 any](seq iter.Seq2[K1, V1], iteratee func(k K1, v V1) (K2, V2)) iter.Seq2[K2, V2]

func Map2To1

func Map2To1[K, V, R any](seq iter.Seq2[K, V], iteratee func(k K, v V) R) iter.Seq[R]

func MaxTime

func MaxTime(t time.Time, u ...time.Time) time.Time

func Merge

func Merge[K comparable, V any, M ~map[K]V](base M, override ...M) M

Merge multiple maps into a single map. Keys in later maps override keys in earlier maps. If base is nil, a new map is created.

func MergeFromSlice

func MergeFromSlice[M ~map[K]V, S ~[]V, K comparable, V any](base M, toKey func(v V) K, override ...S) M

MergeFromSlice merges a slice of values into a map, using a keyFunc to extract keys from values. If base is nil, a new map is created. Values in the slice override existing values in base if their keys are the same.

func MinTime

func MinTime(t time.Time, u ...time.Time) time.Time

func Past

func Past(t time.Time) bool

Past reports whether t is before time.Now(). It is shorthand for t.Before(time.Now()).

func PositiveMod

func PositiveMod[R constraints.Integer | constraints.Float](x, d R) R

PositiveMod computes the true mathematical modulo of x/d, which is always non-negative. It handles both integer and float types efficiently. For example, PositiveMod(-5, 3) returns 1.

func ProjectRoot

func ProjectRoot() string

ProjectRoot returns the absolute path of the project root directory by finding the go.mod file. It returns an empty string if go.mod is not found.

func Range

func Range[T constraints.Integer | constraints.Float](elementNum int) iter.Seq[T]

func RangeFrom

func RangeFrom[T constraints.Integer | constraints.Float](start T, elementNum int) iter.Seq[T]

func RangeWithSteps

func RangeWithSteps[T constraints.Integer | constraints.Float](start, end, step T) iter.Seq[T]

func RecvContext

func RecvContext[T any](ctx context.Context, ch <-chan T) (T, error)

RecvContext receives a value from the channel ch. It returns when a value is received or the context is done. If the context is done, it returns the context's error. If the channel is closed while waiting for a value, it returns ErrChClosed.

func Repeat

func Repeat[R constraints.Integer | constraints.Float](x, start, end R) R

Repeat attempts to wrap the value x into the range [start, end).

It computes the result based on `math.Mod(x - start, end - start) + start`. Due to the behavior of `math.Mod`, if `x` is already less than `start`, the function may return a value outside the desired range. For a behavior that correctly wraps all values into the range, see `Wrap`.

Examples:

Repeat(12, 0, 10) returns 2
Repeat(5, 0, 10) returns 5
Repeat(3, 5, 10) returns 3 (note: not wrapped into [5, 10))

func Round

func Round[I constraints.Integer, F constraints.Float](x F) I

Round returns the nearest integer value to x, rounding half away from zero. It supports generic Integer and Float types.

Special cases are:

Round(±0) = ±0
Round(±Inf) = ±Inf
Round(NaN) = NaN

func RoundToEven

func RoundToEven[I constraints.Integer, F constraints.Float](x F) I

RoundToEven returns the nearest integer, rounding ties to even. It supports generic Integer and Float types.

Special cases are:

RoundToEven(±0) = ±0
RoundToEven(±Inf) = ±Inf
RoundToEven(NaN) = NaN

func SliceToIndexMap

func SliceToIndexMap[T comparable, S ~[]T](slice S) map[T]int

SliceToIndexMap converts a slice into a map where keys are slice elements and values are their original indices. If there are duplicate elements, the last occurrence's index will be stored.

func SliceToIndexMapBy

func SliceToIndexMapBy[K comparable, V any, S ~[]V](slice S, toKey func(item V) K) map[K]int

SliceToIndexMapBy converts a slice of values into a map where keys are transformed from slice elements using a transform function, and values are their original indices. If there are duplicate transformed keys, the last occurrence's index will be stored.

func Sorted

func Sorted[S ~[]T, T any, P1 Ordered](
	slice S, keys func(item T) P1,
) (sorted []T)

Sorted sorts a slice by a single key.

func Sorted2

func Sorted2[S ~[]T, T any, P1, P2 Ordered](
	slice S, keys func(item T) (P1, P2),
) (sorted []T)

Sorted2 sorts a slice by two keys.

func Sorted3

func Sorted3[S ~[]T, T any, P1, P2, P3 Ordered](
	slice S, keys func(item T) (P1, P2, P3),
) (sorted []T)

Sorted3 sorts a slice by three keys.

func Sorted4

func Sorted4[S ~[]T, T any, P1, P2, P3, P4 Ordered](
	slice S, keys func(item T) (P1, P2, P3, P4),
) (sorted []T)

Sorted4 sorts a slice by four keys.

func Sorted5

func Sorted5[S ~[]T, T any, P1, P2, P3, P4, P5 Ordered](
	slice S, keys func(item T) (P1, P2, P3, P4, P5),
) (sorted []T)

Sorted5 sorts a slice by five keys.

func Sorted6

func Sorted6[S ~[]T, T any, P1, P2, P3, P4, P5, P6 Ordered](
	slice S, keys func(item T) (P1, P2, P3, P4, P5, P6),
) (sorted []T)

Sorted6 sorts a slice by six keys.

func StartOfDay

func StartOfDay(t time.Time) time.Time

StartOfDay returns the start of the day (00:00:00) for the given time in its timezone.

For example:

StartOfDay(2025-08-08 15:30:00 JST) = 2025-08-08 00:00:00 JST

func StrFTime

func StrFTime(str string) time.Time

StrFTime parses a string into a time.Time object. It is equivalent to SQL's `strftime('%s', ?, 'utc')` for parsing. It uses time.DateTime format and time.Local location.

For example:

StrFTime("2006-01-02 15:04:05") = 2006-01-02 15:04:05 +0900 JST

func SubUnsigned

func SubUnsigned[N constraints.Unsigned](a, b N) N

SubUnsigned performs subtraction for unsigned integers, preventing underflow. If a is less than b, it returns 0 instead of a negative result that would wrap around to a large positive number.

func TimeDivMod

func TimeDivMod(t time.Time, d time.Duration) (div time.Time, mod time.Duration)

TimeDivMod divides a time t by a duration d, returning the quotient and remainder.

This function uses standard UTC-based truncation.

func TimeDivModLocal

func TimeDivModLocal(t time.Time, d time.Duration) (div time.Time, mod time.Duration)

TimeDivModLocal divides a time t by a duration d in the time's local timezone, returning the quotient and remainder.

func TimeMod

func TimeMod(t time.Time, d time.Duration) time.Duration

TimeMod returns the remainder of t divided by d.

This function uses standard UTC-based truncation.

func TimeModLocal

func TimeModLocal(t time.Time, d time.Duration) time.Duration

TimeModLocal returns the remainder of t divided by d in the time's local timezone.

func TimeNear

func TimeNear(t time.Time, d time.Duration) time.Duration

TimeNear calculates how close a time t is to the nearest boundary of duration d. It returns 0 if t is on a boundary and d/2 if t is exactly in the middle.

This function uses standard UTC-based truncation.

func TimeNearLocal

func TimeNearLocal(t time.Time, d time.Duration) time.Duration

TimeNearLocal calculates how close a time t is to the nearest boundary of duration d in the time's local timezone. It returns 0 if t is on a boundary and d/2 if t is exactly in the middle.

func TimeRange

func TimeRange(times []time.Time) time.Duration

func Trunc

func Trunc[I constraints.Integer, F constraints.Float](x F) I

Trunc returns the integer value of x. It supports generic Integer and Float types.

Special cases are:

Trunc(±0) = ±0
Trunc(±Inf) = ±Inf
Trunc(NaN) = NaN

func TruncateLocal

func TruncateLocal(t time.Time, d time.Duration) time.Time

TruncateLocal truncates a time to a multiple of d in its local timezone.

For example:

TruncateLocal(2025-08-08 15:30:00 JST, 24 * time.Hour) = 2025-08-08 00:00:00 JST

func UniformBy

func UniformBy[T any, S ~[]T, C comparable](s S, predicate func(T) C) bool

allEqual

func WeekOfMonth

func WeekOfMonth(t time.Time, startOfWeek time.Weekday) int

WeekOfMonth returns the week number of the month for the given time, based on a custom start day of the week. Week 1 starts with the first occurrence of `startOfWeek` in the month.

For example:

WeekOfMonth(2025-08-09 (Saturday), Monday) = 2

func WeekOfYearISO deprecated

func WeekOfYearISO(t time.Time) int

Deprecated: Use time.Time.ISOWeek() instead. WeekOfYearISO returns the ISO 8601 week number of the year. Week 1 is the first week with at least 4 days in the new year, and starts on Monday.

func WithNotifyContext

func WithNotifyContext(parent context.Context) (ctx context.Context, stop context.CancelFunc)

WithNotifyContext wraps signal.NotifyContext. It returns a copy of the parent context that is canceled when the process receives a SIGTERM, os.Interrupt, or os.Kill signal.

func WithinRange

func WithinRange(t time.Time, interval, tolerance time.Duration) bool

WithinRange checks if t is within ±tolerance (inclusive) of a time rounded to the nearest interval.

For example:

WithinRange(t, 1h, 5m) checks if t is between 9:55:00 and 10:05:00 (inclusive) for a round hour.

Types

type Ordered

type Ordered interface {
	cmp.Ordered | ~bool
}

Ordered is a constraint that permits any type that is ordered by the Go language. This includes all integer, float, and string types, as well as bool.

Jump to

Keyboard shortcuts

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