### Install samber/lo Go Package Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Command to install the samber/lo Go package with version management. This command fetches the specified version of the library, ensuring compatibility with your project. ```bash go get github.com/samber/lo@v1 ``` -------------------------------- ### Install development dependencies with make tools (Shell) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index This command installs necessary development tools and dependencies required for working on the project. It's typically used to set up the local development environment. ```bash make tools ``` -------------------------------- ### Development Workflow Commands Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 This snippet outlines essential commands for contributing to the project, including installing development dependencies and running tests. `make tools` installs necessary tools, while `make test` runs the test suite, and `make watch-test` provides continuous testing. ```shell # Install some dev dependencies make tools # Run tests make test # or make watch-test ``` -------------------------------- ### Create Numerical Range Slice from Start (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Creates a slice of numbers starting from a specified value with a given length. Supports integer and float types. ```Go func RangeFrom[T constraints.Integer | constraints.Float](start T, elementNum int) []T ``` -------------------------------- ### Check for Sequence Prefix (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it HasPrefix returns true if the collection starts with the specified prefix. It iterates at most the length of the prefix. This is efficient for checking initial elements. ```Go func HasPrefix[T comparable](collection iter.Seq[T], prefix ...T) bool { // Implementation details... } ``` -------------------------------- ### Generate Sequence of Numbers from Start (RangeFrom) (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it RangeFrom creates a sequence of numbers of a specified type (integer or float) starting from a given value and with a specified length. This function generates a sequence of numbers. ```go func RangeFrom[T constraints.Integer | constraints.Float](start T, elementNum int) iter.Seq[T] ``` -------------------------------- ### Generate Number Sequence with Steps in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Creates a sequence of numbers (positive and/or negative) progressing from start up to, but not including end. A step set to zero will return an empty sequence. Supports integer and float types. ```go func RangeWithSteps[T constraints.Integer | constraints.Float](start, end, step T) iter.Seq[T] ``` -------------------------------- ### RangeWithSteps Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Creates a sequence of numbers progressing from start up to, but not including, end with a specified step. A step of zero returns an empty sequence. ```APIDOC ## RangeWithSteps ### Description Creates a sequence of numbers (positive and/or negative) progressing from start up to, but not including end. step set to zero will return an empty sequence. ### Method N/A (Function Signature) ### Endpoint N/A (Function Signature) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Generate Integer Ranges (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Provides functions to generate slices of integers within specified ranges. This includes creating a range of a certain number of elements, a range starting from a specific value, and a range with a defined step. ```go func Range(elementNum int) []int func RangeFrom(start T, elementNum int) []T func RangeWithSteps(start, end, step T) []T ``` -------------------------------- ### Keys: Get map keys in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index Creates a slice containing all keys from one or more maps. The UniqKeys variant can be used to get only unique keys. ```go package main import ( "fmt" "github.com/samber/lo" ) func main() { keys1 := lo.Keys(map[string]int{"foo": 1, "bar": 2}) fmt.Printf("%v\n", keys1) keys2 := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) fmt.Printf("%v\n", keys2) keys3 := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3}) fmt.Printf("%v\n", keys3) } ``` -------------------------------- ### Slice Collection Safely (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Returns a copy of a slice from a start index up to, but not including, an end index. This function is similar to standard Go slicing `slice[start:end]` but avoids panics on overflow. It handles cases where the end index exceeds the slice length or when the start index is greater than the end index. ```go package main import ( "fmt" "github.com/samber/lo" ) func main() { in := []int{0, 1, 2, 3, 4} slice := lo.Slice(in, 0, 5) fmt.Println(slice) // Output: [0 1 2 3 4] slice = lo.Slice(in, 2, 3) fmt.Println(slice) // Output: [2] slice = lo.Slice(in, 2, 6) fmt.Println(slice) // Output: [2 3 4] slice = lo.Slice(in, 4, 3) fmt.Println(slice) // Output: [] } ``` -------------------------------- ### Import samber/lo Package and Aliases Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Demonstrates how to import the samber/lo library and its sub-packages with specific aliases for different functionalities. This allows for organized usage of the library's utilities. ```go import ( "github.com/samber/lo" lop "github.com/samber/lo/parallel" lom "github.com/samber/lo/mutable" loi "github.com/samber/lo/it" ) ``` -------------------------------- ### Extract Substring - Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Returns a portion of a string based on start index and length. Handles negative start indices and maximum length values for flexible substring extraction. ```go sub := lo.Substring("hello", 2, 3) // "llo" sub := lo.Substring("hello", -4, 3) // "ell" sub := lo.Substring("hello", -2, math.MaxUint) // "lo" ``` -------------------------------- ### Create Sliding Windows of a Sequence in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Creates a sequence of sliding windows of a given size with a specified step. It yields only full-size windows, discarding any partial window at the end. The `offset` (step - size) determines overlap or gaps between windows. ```Go func Sliding[T any](collection iter.Seq[T], size, step int) iter.Seq[[]T] ``` -------------------------------- ### Create Sliding Windows: Window (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Creates a slice of sliding windows of a given size. Each window overlaps with the previous one by size-1 elements. This is equivalent to `Sliding(collection, size, 1)`. Requires the 'lo' package. ```go package main import ( "fmt" "github.com/samber/lo" ) func main() { window1 := lo.Window([]int{1, 2, 3, 4, 5}, 3) fmt.Println(window1) window2 := lo.Window([]float64{20, 22, 21, 23, 24}, 3) fmt.Println(window2) } ``` -------------------------------- ### Try-Catch Execution with Callbacks (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Allows executing a function and providing a callback for error handling (catching panics). It includes variations that can capture the error value or perform specific actions on success or failure. These functions are designed for robust error management. ```go func TryCatch(callback func() error, catch func()) func TryCatchWithErrorValue(callback func() error, catch func(any)) func TryWithErrorValue(callback func() error) (errorValue any, ok bool) ``` -------------------------------- ### Repeat with Callback in Sequence in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Builds a sequence by calling a callback function a specified number of times. The callback function generates the value for each element based on its index. ```go func RepeatBy[T any](count int, callback func(index int) T) iter.Seq[T] ``` -------------------------------- ### Get Empty Value or Sample Element (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Provides functions to get an empty value of a generic type `T` or to sample a single element from a collection. `Sample` returns an arbitrary element, while `Samples` returns a specified number of random elements. ```go func Empty() T func Sample(collection []T) T func Samples(collection []T, count int) []T ``` -------------------------------- ### Get the Last Element or Zero Value Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it LastOrEmpty returns the last element of a sequence, or the zero value of the element type if the sequence is empty. It iterates through the entire sequence. This is a convenient way to get the last item without explicit empty checks. ```go func LastOrEmpty[T any](collection iter.Seq[T]) T ``` -------------------------------- ### Execute Function and Handle Errors with 'Try' (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Provides a set of utility functions to safely execute a function that might return an error. These functions catch panics and return a boolean indicating success or failure. Different 'Try' functions handle varying numbers of return values. ```go func Try(callback func() error) (ok bool) func Try0(callback func()) bool func Try1(callback func() error) bool func Try2(callback func() (T, error)) bool func Try3(callback func() (T, R, error)) bool func Try4(callback func() (T, R, S, error)) bool func Try5(callback func() (T, R, S, Q, error)) bool func Try6(callback func() (T, R, S, Q, U, error)) bool ``` -------------------------------- ### Switch Statement Helper (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index Provides a fluent API for creating switch statements. Allows defining cases and a default value in a chainable manner. ```Go package lo // switchCase is an internal struct to build switch statements. type switchCase[T comparable, R any] struct { predicate T value R next *switchCase[T, R] defaultVal R isDefault bool } // Switch starts a fluent switch statement with a given predicate value. func Switch[T comparable, R any](predicate T) *switchCase[T, R] { // Implementation omitted for brevity return nil } // Case adds a case to the switch statement. func (sc *switchCase[T, R]) Case(value T) *switchCase[T, R] { // Implementation omitted for brevity return nil } // Default sets the default value for the switch statement. func (sc *switchCase[T, R]) Default(value R) *switchCase[T, R] { // Implementation omitted for brevity return nil } // Value returns the result of the switch statement. func (sc *switchCase[T, R]) Value() R { // Implementation omitted for brevity var zero R return zero } ``` -------------------------------- ### Get Last Element or Zero Value (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Returns the last element of a collection or its zero value if the collection is empty. This function provides a convenient way to get the last item without explicit nil or empty checks, defaulting to the type's zero value. ```go package main import ( "fmt" "github.com/samber/lo" ) func main() { last := lo.LastOrEmpty([]int{1, 2, 3}) // last is 3 fmt.Println(last) last = lo.LastOrEmpty([]int{}) // last is 0 fmt.Println(last) } ``` -------------------------------- ### Function Partial Application Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Functions to create new functions with some arguments pre-filled. ```APIDOC ## Partial ### Description Partial returns a new function that, when called, has its first argument set to the provided value. ### Method `func Partial[T1, T2, R any](f func(a T1, b T2) R, arg1 T1) func(T2) R` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **func(T2) R** - A function that takes the second argument and returns the result. #### Response Example None ## Partial1 ### Description Partial1 returns a new function that, when called, has its first argument set to the provided value. ### Method `func Partial1[T1, T2, R any](f func(T1, T2) R, arg1 T1) func(T2) R` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **func(T2) R** - A function that takes the second argument and returns the result. #### Response Example None ## Partial2 ### Description Partial2 returns a new function that, when called, has its first argument set to the provided value. ### Method `func Partial2[T1, T2, T3, R any](f func(T1, T2, T3) R, arg1 T1) func(T2, T3) R` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **func(T2, T3) R** - A function that takes the second and third arguments and returns the result. #### Response Example None ## Partial3 ### Description Partial3 returns a new function that, when called, has its first argument set to the provided value. ### Method `func Partial3[T1, T2, T3, T4, R any](f func(T1, T2, T3, T4) R, arg1 T1) func(T2, T3, T4) R` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **func(T2, T3, T4) R** - A function that takes the second, third, and fourth arguments and returns the result. #### Response Example None ## Partial4 ### Description Partial4 returns a new function that, when called, has its first argument set to the provided value. ### Method `func Partial4[T1, T2, T3, T4, T5, R any](f func(T1, T2, T3, T4, T5) R, arg1 T1) func(T2, T3, T4, T5) R` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **func(T2, T3, T4, T5) R** - A function that takes the second, third, fourth, and fifth arguments and returns the result. #### Response Example None ## Partial5 ### Description Partial5 returns a new function that, when called, has its first argument set to the provided value. ### Method `func Partial5[T1, T2, T3, T4, T5, T6, R any](f func(T1, T2, T3, T4, T5, T6) R, arg1 T1) func(T2, T3, T4, T5, T6) R` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **func(T2, T3, T4, T5, T6) R** - A function that takes the second, third, fourth, fifth, and sixth arguments and returns the result. #### Response Example None ``` -------------------------------- ### Get First Element or Zero Value (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Returns the first element of a collection or its zero value if the collection is empty. This function provides a convenient way to get the first item without explicit nil or empty checks, defaulting to the type's zero value. ```go package main import ( "fmt" "github.com/samber/lo" ) func main() { first := lo.FirstOrEmpty([]int{1, 2, 3}) // first is 1 fmt.Println(first) first = lo.FirstOrEmpty([]int{}) // first is 0 fmt.Println(first) } ``` -------------------------------- ### Create a Map by Keying Elements (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Creates a map from a collection by applying an iteratee function to each element. The iteratee function extracts a key from each element, which is then used as the key in the resulting map. This function is generic for key type `K` and value type `V`. ```go func KeyBy(collection []V, iteratee func(V) K) map[K]V ``` -------------------------------- ### Slice Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Returns a sub-slice from `start` up to, but not including, `end`. Does not panic on overflow. ```APIDOC ## Slice ### Description Returns a slice from `start` up to, but not including `end`. Like `slice[start:end]`, but does not panic on overflow. ### Method `func Slice[T any, Slice ~[]T](collection Slice, start, end int) Slice` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - `Slice` (slice): The resulting sub-slice. #### Response Example None ``` -------------------------------- ### Partial5: Create a function with the first argument pre-filled (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Partial5 returns a new function that takes the remaining arguments of the original function. The first argument is fixed to the value provided to Partial5. This is a specific implementation for functions with six arguments. ```Go func Partial5[T1, T2, T3, T4, T5, T6, R any](f func(T1, T2, T3, T4, T5, T6) R, arg1 T1) func(T2, T3, T4, T5, T6) R ``` -------------------------------- ### Get Unique Values from Multiple Maps (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Extracts all unique values from one or more maps. Returns a slice containing the unique values. ```Go func UniqValues[K comparable, V comparable](in ...map[K]V) []V ``` -------------------------------- ### Create a Keyed Throttling Function (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Creates a throttling function that limits the execution rate of another function based on a key. It returns a throttle function and a reset function. ```Go func NewThrottleBy[T comparable](interval time.Duration, f ...func(key T)) (throttle func(key T), reset func()) ``` -------------------------------- ### Get Unique Keys from Multiple Maps (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Extracts all unique keys from one or more maps. Returns a slice containing the unique keys. ```Go func UniqKeys[K comparable, V any](in ...map[K]V) []K ``` -------------------------------- ### Sample: Get Random Element from Slice (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Sample returns a single random element from a slice. The selection is uniformly random. ```go func Sample[T any](collection []T) T ``` -------------------------------- ### Convert String to CamelCase Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index Converts a string to camelCase, where the first letter of the string is lowercase and subsequent words start with an uppercase letter. ```go package main import "github.com/samber/lo" func main() { str := lo.CamelCase("hello_world") // str == "helloWorld" } ``` -------------------------------- ### Channel Fan-In and Fan-Out (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index Utilities for managing concurrent operations using channels. `FanIn` merges multiple input channels into one, while `FanOut` distributes elements from one channel to multiple output channels. ```Go func FanIn[T any](channelBufferCap int, upstreams ...<-chan T) <-chan T func FanOut[T any](count, channelsBufferCap int, upstream <-chan T) []<-chan T ``` -------------------------------- ### Create a Set (Map) of Unique Sequence Elements Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Keyify creates a map where each unique element from the input sequence becomes a key, with an empty struct as the value. It iterates through the entire sequence. This effectively creates a set for fast membership checking. ```go func Keyify[T comparable](collection iter.Seq[T]) map[T]struct{} ``` -------------------------------- ### Get Rune Length of String Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index Returns the number of Unicode code points (runes) in a string. This is an alias for `utf8.RuneCountInString` and differs from the byte length. ```go package main import "github.com/samber/lo" func main() { runeLen := lo.RuneLength("hellĂ´") // runeLen == 5 byteLen := len("hellĂ´") // byteLen == 6 } ``` -------------------------------- ### Tuple and Unpacking Functions in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Provides utility functions for creating and unpacking tuples of various sizes (2 to 9 elements). These are useful for returning multiple values from functions, especially in concurrent scenarios. ```Go type Tuple2[A any, B any] func T2[A any, B any](a A, b B) Tuple2[A, B] func Unpack2[A any, B any](tuple Tuple2[A, B]) (A, B) type Tuple3[A any, B any, C any] func T3[A any, B any, C any](a A, b B, c C) Tuple3[A, B, C] func Unpack3[A any, B any, C any](tuple Tuple3[A, B, C]) (A, B, C) type Tuple4[A any, B any, C any, D any] func T4[A any, B any, C any, D any](a A, b B, c C, d D) Tuple4[A, B, C, D] func Unpack4[A any, B any, C any, D any](tuple Tuple4[A, B, C, D]) (A, B, C, D) type Tuple5[A any, B any, C any, D any, E any] func T5[A any, B any, C any, D any, E any](a A, b B, c C, d D, e E) Tuple5[A, B, C, D, E] func Unpack5[A any, B any, C any, D any, E any](tuple Tuple5[A, B, C, D, E]) (A, B, C, D, E) type Tuple6[A any, B any, C any, D any, E any, F any] func T6[A any, B any, C any, D any, E any, F any](a A, b B, c C, d D, e E, f F) Tuple6[A, B, C, D, E, F] func Unpack6[A any, B any, C any, D any, E any, F any](tuple Tuple6[A, B, C, D, E, F]) (A, B, C, D, E, F) type Tuple7[A any, B any, C any, D any, E any, F any, G any] func T7[A any, B any, C any, D any, E any, F any, G any](a A, b B, c C, d D, e E, f F, g G) Tuple7[A, B, C, D, E, F, G] func Unpack7[A any, B any, C any, D any, E any, F any, G any](tuple Tuple7[A, B, C, D, E, F, G]) (A, B, C, D, E, F, G) type Tuple8[A any, B any, C any, D any, E any, F any, G any, H any] func T8[A any, B any, C any, D any, E any, F any, G any, H any](a A, b B, c C, d D, e E, f F, g G, h H) Tuple8[A, B, C, D, E, F, G, H] func Unpack8[A any, B any, C any, D any, E any, F any, G any, H any](tuple Tuple8[A, B, C, D, E, F, G, H]) (A, B, C, D, E, F, G, H) type Tuple9[A any, B any, C any, D any, E any, F any, G any, H any, I any] func T9[A any, B any, C any, D any, E any, F any, G any, H any, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I) Tuple9[A, B, C, D, E, F, G, H, I] func Unpack9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tuple Tuple9[A, B, C, D, E, F, G, H, I]) (A, B, C, D, E, F, G, H, I) ``` -------------------------------- ### Get Current Time - xtime Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/internal/xtime Retrieves the current time. This function is part of the xtime package, which mocks the standard Go time package. ```Go func Now() time.Time ``` -------------------------------- ### Keyify Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Keyify returns a map with each unique element of the slice as a key. ```APIDOC ## Keyify ### Description Keyify returns a map with each unique element of the slice as a key. ### Method GET ### Endpoint /websites/pkg_go_dev_github_com_samber_lo_v1_53_0/Keyify ### Parameters #### Query Parameters - **collection** (slice) - Required - The slice to convert into map keys. ### Response #### Success Response (200) - **result** (map) - A map where keys are the unique elements of the slice. ### Response Example ```json { "result": { "a": {}, "b": {}, "d": {} } } ``` ``` -------------------------------- ### Zip Five Sequences (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Combines five sequences into a single sequence of 5-element tuples. Each tuple contains corresponding elements from the input sequences. The resulting sequence's length is determined by the shortest input sequence. ```Go func Zip5[A, B, C, D, E any](a iter.Seq[A], b iter.Seq[B], c iter.Seq[C], d iter.Seq[D], e iter.Seq[E]) iter.Seq[lo.Tuple5[A, B, C, D, E]] ``` -------------------------------- ### Check for Prefix/Suffix in Collection (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Verifies if a collection starts or ends with a specified prefix or suffix sequence. Applicable to comparable element types. ```go func HasPrefix[T comparable](collection, prefix []T) bool func HasSuffix[T comparable](collection, suffix []T) bool ``` -------------------------------- ### Drop Elements from Sequence Start with Drop in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it The Drop function removes a specified number of elements (n) from the beginning of a sequence. It returns a new sequence of the same type. ```Go func Drop[T any, I ~func(func(T) bool)](collection I, n int) I ``` -------------------------------- ### v1.37.0 - Partial Application Functions Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Provides functions for partial application, allowing you to create new functions with some arguments pre-filled. ```APIDOC ## Partial Application Functions ### Description Provides functions for partial application, allowing you to create new functions with some arguments pre-filled. ### Functions - **Partial1**: Partially applies the first argument to a function. - **Partial2**: Partially applies the first argument to a function of three arguments. - **Partial3**: Partially applies the first argument to a function of four arguments. - **Partial4**: Partially applies the first argument to a function of five arguments. - **Partial5**: Partially applies the first argument to a function of six arguments. ### Method N/A (Functions) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### String Manipulation: Trim Prefix from Slice Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Removes a specified prefix from the beginning of a slice. If the slice does not start with the prefix, it is returned unchanged. Works with comparable element types. ```go func TrimPrefix[T comparable, Slice ~[]T](collection, prefix Slice) Slice ``` -------------------------------- ### Create Sliding Windows with Step: Sliding (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Creates a slice of sliding windows of a given size with a specified step. If step equals size, windows are non-overlapping (like Chunk). If step is less than size, windows overlap. Requires the 'lo' package. ```go package main import ( "fmt" "github.com/samber/lo" ) func main() { // Windows with shared elements (step < size) sliding1 := lo.Sliding([]int{1, 2, 3, 4, 5, 6}, 3, 1) fmt.Println(sliding1) // Windows with no shared elements (step == size, like Chunk) sliding2 := lo.Sliding([]int{1, 2, 3, 4, 5, 6}, 3, 3) fmt.Println(sliding2) // Step > size (skipping elements) sliding3 := lo.Sliding([]int{1, 2, 3, 4, 5, 6, 7, 8}, 2, 3) fmt.Println(sliding3) } ``` -------------------------------- ### Create New FakeClock - xtime Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/internal/xtime Constructs a new instance of FakeClock. This function initializes a fake clock, typically starting at the zero time. ```Go func NewFakeClock() *FakeClock ``` -------------------------------- ### Iterate with Index and Apply Callback (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it ForEachI iterates over elements of a collection and invokes a callback function for each element, providing both the item and its index. It will iterate through the entire sequence. ```Go func ForEachI[T any](collection iter.Seq[T], callback func(item T, index int)) { // Implementation details... } ``` -------------------------------- ### Get Pointer Value or Fallback (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 FromPtrOr dereferences a pointer to type T and returns its value. If the pointer is nil, it returns the provided fallback value. ```Go func FromPtrOr[T any](x *T, fallback T) T ``` -------------------------------- ### Keyify Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Returns a map with each unique element of the sequence as a key. Iterates through the entire sequence. ```APIDOC ## Keyify ### Description Creates a map where keys are the unique elements of the sequence. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) Returns a `map[T]struct{}` where `T` is the element type. #### Response Example N/A ``` -------------------------------- ### Get Value from Pointer (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 FromPtr dereferences a pointer to type T and returns its value. If the pointer is nil, it returns the zero value for type T. ```Go func FromPtr[T any](x *T) T ``` -------------------------------- ### Zip Seven Sequences (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Combines seven sequences into a single sequence of 7-element tuples. Each tuple contains corresponding elements from the input sequences. The resulting sequence's length is determined by the shortest input sequence. ```Go func Zip7[A, B, C, D, E, F, G any](a iter.Seq[A], b iter.Seq[B], c iter.Seq[C], d iter.Seq[D], e iter.Seq[E], f iter.Seq[F], g iter.Seq[G]) iter.Seq[lo.Tuple7[A, B, C, D, E, F, G]] ``` -------------------------------- ### Run project tests with make test (Shell) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index This command executes the project's test suite. It's essential for verifying the correctness of code changes and ensuring the project remains stable. ```bash make test ``` -------------------------------- ### String Manipulation: Check for Prefix in Slice Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Checks if a slice has a given prefix. Returns true if the slice starts with the specified prefix, false otherwise. Works with comparable element types. ```go func HasPrefix[T comparable](collection, prefix []T) bool ``` -------------------------------- ### Slice Sequence - Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it_tab=versions Extracts a sub-sequence (slice) from a given sequence based on start and end indices. This allows for selecting a specific portion of the sequence for further processing. ```go func Slice[T any, I ~func(func(T) bool)](collection I, start, end int) I ``` -------------------------------- ### ToPtr Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Takes a value of any type 'T' and returns a pointer to a copy of that value. This is useful when you need a pointer to a value, for example, to pass to a function that expects a pointer. ```APIDOC ## ToPtr ### Description Returns a pointer copy of a value. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns a pointer to the input value. #### Response Example ```go // Example usage: value := 5 ptr := ToPtr(value) // ptr will be a pointer to 5 ``` ``` -------------------------------- ### Take First N Elements Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Returns a new slice containing the first `n` elements from the input slice. ```APIDOC ## Take ### Description Takes the first `n` elements from a slice. ### Method N/A (Function Signature) ### Endpoint N/A (Function Signature) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // data := []int{0, 1, 2, 3, 4, 5} // firstThree := Take(data, 3) // fmt.Println(firstThree) // Output: [0 1 2] // data := []int{10, 20} // firstFive := Take(data, 5) // n is larger than slice length // fmt.Println(firstFive) // Output: [10 20] ``` ### Response #### Success Response (200) `Slice`: A new slice containing the first `n` elements, or fewer if the original slice has less than `n` elements. ``` -------------------------------- ### Get Nth Element from Collection (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index Retrieves the element at a specific index (nth) from a collection. Provides variants to return a fallback value or an error if the index is out of bounds. ```go func Nth[T any, N constraints.Integer](collection []T, nth N) (T, error) func NthOr[T any, N constraints.Integer](collection []T, nth N, fallback T) T func NthOrEmpty[T any, N constraints.Integer](collection []T, nth N) T ``` -------------------------------- ### Slice Slicing and Conversion Functions (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index Provides utilities for extracting sub-slices, converting slices to channels or maps, and creating sliding windows over a slice. Includes functions for transforming slice elements into map entries. ```Go package lo // Slice extracts a sub-slice from the given collection between start and end indices. func Slice[T any, Slice ~[]T](collection Slice, start, end int) Slice { // Implementation omitted for brevity return nil } // SliceToChannel converts a slice into a read-only channel with a specified buffer size. func SliceToChannel[T any](bufferSize int, collection []T) <-chan T { // Implementation omitted for brevity return nil } // SliceToMap converts a slice into a map using a transform function to generate keys and values. func SliceToMap[T any, K comparable, V any](collection []T, transform func(item T) (K, V)) map[K]V { // Implementation omitted for brevity return nil } // SliceToMapI converts a slice into a map using a transform function that includes the index. func SliceToMapI[T any, K comparable, V any](collection []T, transform func(item T, index int) (K, V)) map[K]V { // Implementation omitted for brevity return nil } // Sliding creates a slice of slices, where each inner slice is a 'window' of 'size' elements, stepping by 'step'. func Sliding[T any, Slice ~[]T](collection Slice, size, step int) []Slice { // Implementation omitted for brevity return nil } ``` -------------------------------- ### ToPtr: Get a pointer to a value (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 ToPtr takes a value of any type T and returns a pointer to a copy of that value. This is a convenient way to obtain a pointer to a variable or literal. ```Go func ToPtr[T any](x T) *T ``` -------------------------------- ### Type Conversion and Utility Functions Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Functions for type conversions and general utilities. ```APIDOC ## Type Conversion and Utility Functions ### Description Provides functions for type conversions, conditional logic, and error handling. ### Functions #### Ternary * **Signature**: `func Ternary[T any](condition bool, ifOutput, elseOutput T) T` * **Description**: Returns `ifOutput` if `condition` is true, otherwise returns `elseOutput`. #### TernaryF * **Signature**: `func TernaryF[T any](condition bool, ifFunc, elseFunc func() T) T` * **Description**: Returns the result of `ifFunc` if `condition` is true, otherwise returns the result of `elseFunc`. #### Times * **Signature**: `func Times[T any](count int, iteratee func(index int) T) []T` * **Description**: Executes an iteratee function `count` times and collects the results into a slice. #### ToAnySlice * **Signature**: `func ToAnySlice[T any](collection []T) []any` * **Description**: Converts a slice of a specific type to a slice of `any` (interface{}) #### ToPtr * **Signature**: `func ToPtr[T any](x T) *T` * **Description**: Returns a pointer to the given value. #### ToSlicePtr * **Signature**: `func ToSlicePtr[T any](collection []T) []*T` * **Description**: Converts a slice of values to a slice of pointers to those values. #### Trim * **Signature**: `func Trim[T comparable, Slice ~[]T](collection, cutset Slice) Slice` * **Description**: Removes leading and trailing elements from a slice that are present in the `cutset`. #### TrimLeft * **Signature**: `func TrimLeft[T comparable, Slice ~[]T](collection, cutset Slice) Slice` * **Description**: Removes leading elements from a slice that are present in the `cutset`. #### TrimPrefix * **Signature**: `func TrimPrefix[T comparable, Slice ~[]T](collection, prefix Slice) Slice` * **Description**: Removes a prefix slice from the beginning of a slice if it matches. #### TrimRight * **Signature**: `func TrimRight[T comparable, Slice ~[]T](collection, cutset Slice) Slice` * **Description**: Removes trailing elements from a slice that are present in the `cutset`. #### TrimSuffix * **Signature**: `func TrimSuffix[T comparable, Slice ~[]T](collection, suffix Slice) Slice` * **Description**: Removes a suffix slice from the end of a slice if it matches. #### Try * **Signature**: `func Try(callback func() error) (ok bool)` * **Description**: Executes a callback function that returns an error. Returns `true` if no error occurred, `false` otherwise. #### Try0 * **Signature**: `func Try0(callback func()) bool` * **Description**: Executes a callback function that returns no error. Always returns `true`. #### Try1 * **Signature**: `func Try1(callback func() error) bool` * **Description**: Executes a callback function that returns an error. Returns `true` if no error occurred, `false` otherwise. (Similar to Try, potentially redundant or for specific use cases). ``` -------------------------------- ### Dispatching Strategy Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Utilities for creating dispatching strategies. ```APIDOC ## Dispatching Strategy ### Description Provides mechanisms for defining how tasks or items are distributed. ### Functions * **DispatchingStrategyWeightedRandom** * **Signature**: `func DispatchingStrategyWeightedRandom[T any](weights []int) DispatchingStrategy[T]` * **Description**: Creates a weighted random dispatching strategy based on the provided `weights`. ``` -------------------------------- ### Samples: Get Multiple Unique Random Elements (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Samples returns a specified number of unique random elements from a slice. The elements are chosen without replacement. ```go func Samples[T any, Slice ~[]T](collection Slice, count int) Slice ``` -------------------------------- ### Get First Element of a Go Sequence Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it First returns the first element of a sequence and a boolean indicating its presence. It iterates at most once. Useful for checking if a sequence is empty and retrieving the first item simultaneously. ```go func First[T any](collection iter.Seq[T]) (T, bool) { // Implementation details... var zero T return zero, false } ``` -------------------------------- ### Iterate and Apply Callback (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it ForEach iterates over elements of a collection and invokes a callback function for each element. It will iterate through the entire sequence. The callback function receives the current item as an argument. ```Go func ForEach[T any](collection iter.Seq[T], callback func(item T)) { // Implementation details... } ``` -------------------------------- ### Conditional and Utility Functions in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53_tab=versions Includes functions for conditional logic, such as `IfF` for functional-style if-else, and other utilities like `FromPtrOr` for handling pointers with fallback values, and `Clamp` for restricting values within a range. ```Go func FromPtrOr[T any](x *T, fallback T) T func Clamp[T constraints.Ordered](value T, min T, max T) T func IfF[T any](condition bool, resultF func() T) *ifElse[T] func Partial[T1 any, T2 any, R any](f func(T1, T2) R, arg1 T1) func(T2) R ``` -------------------------------- ### Get Sequence Length - Go Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it_tab=versions Calculates the number of elements in a sequence. This function iterates through the sequence to count its items. It's a basic utility for understanding the size of a collection. ```go func Length[T any](collection iter.Seq[T]) int ``` -------------------------------- ### String Substring Extraction (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/index Extracts a portion of a string given a starting offset and a length. The function is generic and can work with string types or types that are string aliases. ```Go package lo // Substring extracts a portion of a string from 'offset' with a specified 'length'. func Substring[T ~string](str T, offset int, length uint) T { // Implementation omitted for brevity var zero T return zero } ``` -------------------------------- ### Zip Eight Sequences (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Combines eight sequences into a single sequence of 8-element tuples. Each tuple contains corresponding elements from the input sequences. The resulting sequence's length is determined by the shortest input sequence. ```Go func Zip8[A, B, C, D, E, F, G, H any](a iter.Seq[A], b iter.Seq[B], c iter.Seq[C], d iter.Seq[D], e iter.Seq[E], f iter.Seq[F], g iter.Seq[G], h iter.Seq[H]) iter.Seq[lo.Tuple8[A, B, C, D, E, F, G, H]] ``` -------------------------------- ### Create New FakeClock at Specific Time - xtime Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/internal/xtime Constructs a new instance of FakeClock initialized to a specific time. This is useful for setting a starting point for time-dependent tests. ```Go func NewFakeClockAt(t time.Time) *FakeClock ``` -------------------------------- ### Benchmark lo.Map vs. Other Implementations Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 This section presents benchmark results comparing `lo.Map` against `lop.Map`, `go-funk`, and a standard Go `for` loop. The benchmarks measure operations per second, bytes allocated per operation, and allocations per operation. ```go _ = lo.Map[int64](arr, func(x int64, i int) string { return strconv.FormatInt(x, 10) }) ``` -------------------------------- ### Get Element at Specific Index (Nth) from Collection (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Nth retrieves the element at a specified index 'nth' from a collection. It returns an error if the index is out of bounds. The function iterates up to 'n' times through the sequence. ```go func Nth[T any, N constraints.Integer](collection iter.Seq[T], nth N) (T, error) ``` -------------------------------- ### Keys Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it Creates a sequence of the map keys. ```APIDOC ## Keys ### Description Extracts the keys from one or more maps into a sequence. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) Returns an `iter.Seq[K]` containing the keys from the input maps. #### Response Example N/A ``` -------------------------------- ### Get First Element or Zero Value in a Go Sequence Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53.0/it FirstOrEmpty returns the first element of a sequence or the zero value of the type if the sequence is empty. It iterates at most once. This is convenient when a zero value is an acceptable default. ```go func FirstOrEmpty[T any](collection iter.Seq[T]) T { // Implementation details... var zero T return zero } ``` -------------------------------- ### Slice: Extract Sub-slice Safely (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.53.0/github.com/samber/lo%40v1.53 Slice returns a portion of a slice from a start index up to (but not including) an end index. It safely handles out-of-bounds indices without panicking. ```go func Slice[T any, Slice ~[]T](collection Slice, start, end int) Slice ```