lo - Iterate over slices, maps, channels...
✨ samber/lo
is a Lodash-style Go library based on Go 1.18+ Generics.
This project started as an experiment with the new generics implementation. It may look like Lodash in some aspects. I used to code with the fantastic "go-funk" package, but "go-funk" uses reflection and therefore is not typesafe.
As expected, benchmarks demonstrate that generics are much faster than implementations based on the "reflect" package. Benchmarks also show similar performance gains compared to pure for
loops. See below.
In the future, 5 to 10 helpers will overlap with those coming into the Go standard library (under package names slices
and maps
). I feel this library is legitimate and offers many more valuable abstractions.
See also:
- samber/do: A dependency injection toolkit based on Go 1.18+ Generics
- samber/mo: Monads based on Go 1.18+ Generics (Option, Result, Either...)
Why this name?
I wanted a short name, similar to "Lodash" and no Go package uses this name.
🚀 Install
go get github.com/samber/lo@v1
This library is v1 and follows SemVer strictly.
No breaking changes will be made to exported APIs before v2.0.0.
This library has no dependencies outside the Go standard library.
💡 Usage
You can import lo
using:
import (
"github.com/samber/lo"
lop "github.com/samber/lo/parallel"
)
Then use one of the helpers below:
names := lo.Uniq([]string{"Samuel", "John", "Samuel"})
// []string{"Samuel", "John"}
Most of the time, the compiler will be able to infer the type so that you can call: lo.Uniq([]string{...})
.
Tips for lazy developers
I cannot recommend it, but in case you are too lazy for repeating lo.
everywhere, you can import the entire library into the namespace.
import (
. "github.com/samber/lo"
)
I take no responsibility on this junk. 😁 💩
🤠 Spec
GoDoc: https://godoc.org/github.com/samber/lo
Supported helpers for slices:
- Filter
- Map
- FilterMap
- FlatMap
- Reduce
- ReduceRight
- ForEach
- ForEachWhile
- Times
- Uniq
- UniqBy
- GroupBy
- Chunk
- PartitionBy
- Flatten
- Interleave
- Shuffle
- Reverse
- Fill
- Repeat
- RepeatBy
- KeyBy
- Associate / SliceToMap
- Drop
- DropRight
- DropWhile
- DropRightWhile
- DropByIndex
- Reject
- RejectMap
- FilterReject
- Count
- CountBy
- CountValues
- CountValuesBy
- Subset
- Slice
- Replace
- ReplaceAll
- Compact
- IsSorted
- IsSortedByKey
- Splice
Supported helpers for maps:
- Keys
- UniqKeys
- HasKey
- ValueOr
- Values
- UniqValues
- PickBy
- PickByKeys
- PickByValues
- OmitBy
- OmitByKeys
- OmitByValues
- Entries / ToPairs
- FromEntries / FromPairs
- Invert
- Assign (merge of maps)
- MapKeys
- MapValues
- MapEntries
- MapToSlice
Supported math helpers:
Supported helpers for strings:
- RandomString
- Substring
- ChunkString
- RuneLength
- PascalCase
- CamelCase
- KebabCase
- SnakeCase
- Words
- Capitalize
- Elipse
Supported helpers for tuples:
Supported helpers for time and duration:
Supported helpers for channels:
Supported intersection helpers:
- Contains
- ContainsBy
- Every
- EveryBy
- Some
- SomeBy
- None
- NoneBy
- Intersect
- Difference
- Union
- Without
- WithoutEmpty
Supported search helpers:
- IndexOf
- LastIndexOf
- Find
- FindIndexOf
- FindLastIndexOf
- FindOrElse
- FindKey
- FindKeyBy
- FindUniques
- FindUniquesBy
- FindDuplicates
- FindDuplicatesBy
- Min
- MinBy
- Earliest
- EarliestBy
- Max
- MaxBy
- Latest
- LatestBy
- First
- FirstOrEmpty
- FirstOr
- Last
- LastOrEmpty
- LastOr
- Nth
- Sample
- Samples
Conditional helpers:
Type manipulation helpers:
- IsNil
- ToPtr
- Nil
- EmptyableToPtr
- FromPtr
- FromPtrOr
- ToSlicePtr
- FromSlicePtr
- FromSlicePtrOr
- ToAnySlice
- FromAnySlice
- Empty
- IsEmpty
- IsNotEmpty
- Coalesce
- CoalesceOrEmpty
Function helpers:
Concurrency helpers:
- Attempt
- AttemptWhile
- AttemptWithDelay
- AttemptWhileWithDelay
- Debounce
- DebounceBy
- Synchronize
- Async
- Transaction
- WaitFor
- WaitForWithContext
Error handling:
- Validate
- Must
- Try
- Try1 -> Try6
- TryOr
- TryOr1 -> TryOr6
- TryCatch
- TryWithErrorValue
- TryCatchWithErrorValue
- ErrorsAs
Constraints:
- Clonable
Filter
Iterates over a collection and returns an array of all the elements the predicate function returns true
for.
even := lo.Filter([]int{1, 2, 3, 4}, func(x int, index int) bool {
return x%2 == 0
})
// []int{2, 4}
[play]
Map
Manipulates a slice of one type and transforms it into a slice of another type:
import "github.com/samber/lo"
lo.Map([]int64{1, 2, 3, 4}, func(x int64, index int) string {
return strconv.FormatInt(x, 10)
})
// []string{"1", "2", "3", "4"}
[play]
Parallel processing: like lo.Map()
, but the mapper function is called in a goroutine. Results are returned in the same order.
import lop "github.com/samber/lo/parallel"
lop.Map([]int64{1, 2, 3, 4}, func(x int64, _ int) string {
return strconv.FormatInt(x, 10)
})
// []string{"1", "2", "3", "4"}
FilterMap
Returns a slice which obtained after both filtering and mapping using the given callback function.
The callback function should return two values: the result of the mapping operation and whether the result element should be included or not.
matching := lo.FilterMap([]string{"cpu", "gpu", "mouse", "keyboard"}, func(x string, _ int) (string, bool) {
if strings.HasSuffix(x, "pu") {
return "xpu", true
}
return "", false
})
// []string{"xpu", "xpu"}
[play]
FlatMap
Manipulates a slice and transforms and flattens it to a slice of another type. The transform function can either return a slice or a nil
, and in the nil
case no value is added to the final slice.
lo.FlatMap([]int64{0, 1, 2}, func(x int64, _ int) []string {
return []string{
strconv.FormatInt(x, 10),
strconv.FormatInt(x, 10),
}
})
// []string{"0", "0", "1", "1", "2", "2"}
[play]
Reduce
Reduces a collection to a single value. The value is calculated by accumulating the result of running each element in the collection through an accumulator function. Each successive invocation is supplied with the return value returned by the previous call.
sum := lo.Reduce([]int{1, 2, 3, 4}, func(agg int, item int, _ int) int {
return agg + item
}, 0)
// 10
[play]
ReduceRight
Like lo.Reduce
except that it iterates over elements of collection from right to left.
result := lo.ReduceRight([][]int{{0, 1}, {2, 3}, {4, 5}}, func(agg []int, item []int, _ int) []int {
return append(agg, item...)
}, []int{})
// []int{4, 5, 2, 3, 0, 1}
[play]
ForEach
Iterates over elements of a collection and invokes the function over each element.
import "github.com/samber/lo"
lo.ForEach([]string{"hello", "world"}, func(x string, _ int) {
println(x)
})
// prints "hello\nworld\n"
[play]
Parallel processing: like lo.ForEach()
, but the callback is called as a goroutine.
import lop "github.com/samber/lo/parallel"
lop.ForEach([]string{"hello", "world"}, func(x string, _ int) {
println(x)
})
// prints "hello\nworld\n" or "world\nhello\n"
ForEachWhile
Iterates over collection elements and invokes iteratee for each element collection return value decide to continue or break, like do while().
list := []int64{1, 2, -42, 4}
lo.ForEachWhile(list, func(x int64, _ int) bool {
if x < 0 {
return false
}
fmt.Println(x)
return true
})
// 1
// 2
[play]
Times
Times invokes the iteratee n times, returning an array of the results of each invocation. The iteratee is invoked with index as argument.
import "github.com/samber/lo"
lo.Times(3, func(i int) string {
return strconv.FormatInt(int64(i), 10)
})
// []string{"0", "1", "2"}
[play]
Parallel processing: like lo.Times()
, but callback is called in goroutine.
import lop "github.com/samber/lo/parallel"
lop.Times(3, func(i int) string {
return strconv.FormatInt(int64(i), 10)
})
// []string{"0", "1", "2"}
Uniq
Returns a duplicate-free version of an array, in which only the first occurrence of each element is kept. The order of result values is determined by the order they occur in the array.
uniqValues := lo.Uniq([]int{1, 2, 2, 1})
// []int{1,