gubrak

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: May 26, 2020 License: MIT Imports: 9 Imported by: 14

README

Gubrak v2

Gubrak is Go functional utility library with syntactic sugar. It's like lodash, but for Go Programming language.

Go Report Card Build Status Coverage Status

Installation

The latest version of gubrak is v2. Here are the available method to get this library.

  • Using go get from github, for Go Mod-based project:

    go get -u github.com/novalagung/gubrak/v2
    
  • Using go get from github, for $GOPATH-based project:

    go get -u github.com/novalagung/gubrak
    

Usage

Since this library is developed as go module, the versioning system used is the one from Go.

  • For Go Mod-based project:

    import gubrak "github.com/novalagung/gubrak/v2"
    
  • For $GOPATH-based project:

    import "github.com/novalagung/gubrak"
    

Documentation

Hello World Example

Lodash for Golang

APIs

Below are the list of available functions on gubrak:

ChunkCompactConcatCountDifferenceDropDropRightEachEachRightFillFilterFindFindIndexFindLastFindLastIndexFirstForEachForEachRightFromPairsGroupByHeadIncludesIndexOfInitialIntersectionIsArrayIsBoolIsChannelIsDateIsEmptyIsEmptyStringIsFloatIsFunctionIsIntIsMapIsNilIsNumericIsPointerIsSliceIsStringIsStructObjectIsTrueIsUintIsZeroNumberJoinKeyByLastLastIndexOfMapNowNthOrderByPartitionPullPullAllPullAtRandomIntRandomStringReduceRejectRemoveReverseSampleSampleSizeShuffleSizeSortByTailTakeTakeRightUnionUniqWithout

Test

go test -cover -race -v ./... 

Contribution

Fork ➜ Create branch ➜ Commit ➜ Push ➜ Pull Requests

License

MIT License

Documentation

Index

Examples

Constants

View Source
const (
	OperationNone             = ""
	OperationChunk            = "Chunk()"
	OperationCompact          = "Compact()"
	OperationConcatMany       = "ConcatMany()"
	OperationConcat           = "Concat()"
	OperationContains         = "Contains()"
	OperationCountBy          = "CountBy()"
	OperationCount            = "Count()"
	OperationDifferenceMany   = "DifferenceMany()"
	OperationDifference       = "Difference()"
	OperationDrop             = "Drop()"
	OperationDropRight        = "DropRight()"
	OperationEach             = "Each()"
	OperationEachRight        = "EachRight()"
	OperationExclude          = "Exclude()"
	OperationExcludeMany      = "ExcludeMany()"
	OperationExcludeAt        = "ExcludeAt()"
	OperationExcludeAtMany    = "ExcludeAtMany()"
	OperationForEach          = "ForEach()"
	OperationForEachRight     = "ForEachRight()"
	OperationFill             = "Fill()"
	OperationFilter           = "Filter()"
	OperationFind             = "Find()"
	OperationFindIndex        = "FindIndex()"
	OperationFindLast         = "FindLast()"
	OperationFindLastIndex    = "FindLastIndex()"
	OperationFirst            = "First()"
	OperationHead             = "Head()"
	OperationFromPairs        = "FromPairs()"
	OperationGroupBy          = "GroupBy()"
	OperationIndexOf          = "IndexOf()"
	OperationInitial          = "Initial()"
	OperationIntersection     = "Intersection()"
	OperationIntersectionMany = "IntersectionMany()"
	OperationJoin             = "Join()"
	OperationKeyBy            = "KeyBy()"
	OperationLast             = "Last()"
	OperationLastIndexOf      = "LastIndexOf()"
	OperationMap              = "Map()"
	OperationNth              = "Nth()"
	OperationOrderBy          = "OrderBy()"
	OperationPartition        = "Partition()"
	OperationReduce           = "Reduce()"
	OperationReject           = "Reject()"
	OperationReverse          = "Reverse()"
	OperationSample           = "Sample()"
	OperationSampleSize       = "SampleSize()"
	OperationShuffle          = "Shuffle()"
	OperationSize             = "Size()"
	OperationTail             = "Tail()"
	OperationTake             = "Take()"
	OperationTakeRight        = "TakeRight()"
	OperationUniq             = "Uniq()"
	OperationUnionMany        = "UnionMany()"
)

Variables

View Source
var IsArrayOrSlice = IsSliceOrArray
View Source
var IsEmpty = IsZeroValue

Functions

func IsArray

func IsArray(data interface{}) bool

IsArray is alias of IsArray()

func IsBool

func IsBool(data interface{}) bool

IsBool will return true when type of the data is boolean

func IsChannel

func IsChannel(data interface{}) bool

IsChannel will return true when type of the data is channel

func IsDate

func IsDate(data interface{}) bool

IsDate will return true when type of the data is time.Time

func IsEmptyString

func IsEmptyString(data interface{}) bool

IsEmptyString will return true when type of the data is string and it's empty

func IsFloat

func IsFloat(data interface{}) bool

IsFloat will return true when type of the data is floating number

func IsFunction

func IsFunction(data interface{}) bool

IsFunction will return true when type of the data is closure/function

func IsInt

func IsInt(data interface{}) bool

IsInt will return true when type of the data is numeric integer

func IsMap

func IsMap(data interface{}) bool

IsMap will return true when type of the data is hash map

func IsNil

func IsNil(data interface{}) bool

IsNil will return true when type of the data is nil

func IsNumeric

func IsNumeric(data interface{}) bool

IsNumeric will return true when type of the data is numeric (float, uint, int)

func IsPointer

func IsPointer(data interface{}) bool

IsPointer will return true when type of the data is pointer

func IsSlice

func IsSlice(data interface{}) bool

IsSlice is alias of IsSlice()

func IsSliceOrArray

func IsSliceOrArray(data interface{}) bool

IsSliceOrArray will return true when type of the data is array/slice

func IsString

func IsString(data interface{}) bool

IsString will return true when type of the data is string

func IsStructObject

func IsStructObject(data interface{}) bool

IsStructObject will return true when type of the data is object from struct

func IsTrue

func IsTrue(data interface{}) bool

IsTrue will return true when type of the data is bool, and the value is true

func IsUint

func IsUint(data interface{}) bool

IsUint will return true when type of the data is uint

func IsZeroNumber

func IsZeroNumber(data interface{}) bool

IsZeroNumber will return true when type of the data is numeric and it's has 0 value

func IsZeroValue

func IsZeroValue(data interface{}) bool

IsZeroValue reports whether value is the zero value for its type.

func RandomInt

func RandomInt(min, max int) int

RandomInt function generates random numeric data between specified min and max

Example
result := RandomInt(10, 12)
fmt.Println(result) // generates random int between 10 to 12 like: 10 or 11 or 12
Output:

func RandomString

func RandomString(length int) string

RandomString function generate random alphabet string in defined length

Example
result := RandomString(32)
fmt.Println(result) // generates random 32 character like: YodQeljldGFluOhaHrlWdICKDtDHSvzA
Output:

func ReplaceCaseInsensitive

func ReplaceCaseInsensitive(text, find, replacement string) string

ReplaceCaseInsensitive function replace all string that match with `find` without caring about it's case

Example
result := ReplaceCaseInsensitive("lOrEm IPsUm DoLor Sit AMEt", "ipsum", "batman")
fmt.Println(result) // lOrEm batman DoLor Sit AMEt
Output:

Types

type Chainable

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

Chainable is base type of gubrak chainable operations

func (*Chainable) Chunk

func (g *Chainable) Chunk(size int) IChainable

Chunk function creates a slice of elements split into groups the length of `size`. If `data` can't be split evenly, the final chunk will be the remaining elements.

Parameters

This function requires single mandatory parameter:

size int // ==> description: the length of each chunk

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Chunk1)
data := []int{1, 2, 3, 4, 5}
size := 2

result := From(data).Chunk(size).Result()
fmt.Println(result)
// ===> [][]int{ { 1, 2 }, { 3, 4 }, { 5 } }
Output:

Example (Chunk2)
data := []string{"a", "b", "c", "d", "e"}
size := 3

result := From(data).Chunk(size).Result()
fmt.Println(result)
// ===> [][]string{ { "a", "b", "c" }, { "d", "e" } }
Output:

Example (Chunk3)
data := []interface{}{
	3.2, "a", -1,
	make([]byte, 0),
	map[string]int{"b": 2},
	[]string{"a", "b", "c"},
}
size := 3

result := From(data).Chunk(size).Result()
fmt.Println(result)
/*
	  [][]interface{}{
		{ 3.2, "a" },
		{ -1, []uint8{} },
		{ map[string]int{ "b":2 }, []string{ "a", "b", "c" } },
	  }
*/ }
*/
Output:

func (*Chainable) Compact

func (g *Chainable) Compact() IChainable

Compact function creates a slice with all falsey values removed from the `data`. These values: `false`, `nil`, `0`, `""`, `(*string)(nil)`, and other nil-able types are considered to be falsey.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Compact1)
data := []int{-2, -1, 0, 1, 2}

result := From(data).Compact().Result()
fmt.Println(result)
// ===> []int{ -2, -1, 1, 2 }
Output:

Example (Compact2)
data := []string{"a", "b", "", "d"}

result := From(data).Compact().Result()
fmt.Println(result)
// ===> []string{ "a", "b", "d" }
Output:

Example (Compact3)
data := []interface{}{-2, 0, 1, 2, false, true, "", "hello", nil}

result := From(data).Compact().Result()
fmt.Println(result)
// ===> []interface{}{ -2, 1, 2, true, "hello" }
Output:

Example (Compact4)
item1, item2, item3 := "a", "b", "c"
data := []*string{&item1, nil, &item2, nil, &item3}

result := From(data).Compact().Result()
fmt.Println(result)
// ===> []*string{ (*string)(0xc42000e1e0), (*string)(0xc42000e1f0), (*string)(0xc42000e200) }
Output:

func (*Chainable) Concat

func (g *Chainable) Concat(sliceToConcat interface{}) IChainable

Concat function creates a new slice concatenating `data` with any additional slice.

Parameters

This function requires single mandatory parameter:

sliceToConcat interface{} // ==> description: the slice to concatenate

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Concat1)
data := []int{1, 2, 3, 4}
dataConcat := []int{4, 6, 7}

result := From(data).Concat(dataConcat).Result()
fmt.Println(result)
// ===> []int{ 1, 2, 3, 4, 5, 6, 7 }
Output:

func (*Chainable) ConcatMany

func (g *Chainable) ConcatMany(slicesToConcat ...interface{}) IChainable

ConcatMany function creates a new slice concatenating `data` with any additional slices (the 2nd parameter and rest).

Parameters

This function requires optional variadic parameters:

sliceToConcat1 interface{} // ==> description: the slice to concatenate
sliceToConcat2 interface{} // ==> description: the slice to concatenate
sliceToConcat3 interface{} // ==> description: the slice to concatenate
...

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Concat1)
data := []int{1, 2, 3, 4}
dataConcat1 := []int{4, 6, 7}
dataConcat2 := []int{8, 9}

result := From(data).ConcatMany(dataConcat1, dataConcat2).Result()
fmt.Println(result)
// ===> []int{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }
Output:

Example (Concat2)
data := []string{"my"}
dataConcat1 := []string{"name", "is"}
dataConcat2 := []string{"jason", "todd"}

result := From(data).ConcatMany(dataConcat1, dataConcat2).Result()
fmt.Println(result)
// ===> []string{ "my", "name", "is", "jason", "todd" }
Output:

func (*Chainable) Contains

func (g *Chainable) Contains(search interface{}, args ...int) IChainableBoolResult

Contains function checks if value is in data. If data is a string, it's checked for a substring of value, otherwise SameValueZero is used for equality comparisons. If `fromIndex` is negative, it's used as the offset from the end of data.

Parameters

This function requires single mandatory parameter:

search interface{} // ==> description: the value to search for.
fromIndex int      // ==> optional
                   //     description: The index to search from
                   //     default value: 0

Return values

Chain with these methods to get result:

.Result() bool                  // ==> description: returns true if value is found, else false
.ResultAndError() (bool, error) // ==> description: returns true if value is found, else false, and error object
.Error() error                  // ==> description: returns error object
.IsError() bool                 // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (ContainsMap1)
data := map[string]string{
	"name":  "grayson",
	"hobby": "helping people",
}

result := From(data).Contains("grayson").Result()

fmt.Println(result)
// ===> true
Output:

Example (ContainsMap2)
data := map[string]string{
	"name":  "grayson",
	"hobby": "helping people",
}

result := From(data).Contains("batmobile").Result()

fmt.Println(result)
// ===> false
Output:

Example (ContainsSlice1)
data := []string{"damian", "tim", "jason", "grayson"}

result := From(data).Contains("tim").Result()

fmt.Println(result)
// ===> true
Output:

Example (ContainsSlice2)
data := []string{"damian", "tim", "jason", "grayson"}

result := From(data).Contains("tim", 2).Result()

fmt.Println(result)
// ===> false
Output:

Example (ContainsSlice3)
data := []string{"damian", "tim", "jason", "grayson"}

result := From(data).Contains("cassandra").Result()

fmt.Println(result)
// ===> false
Output:

Example (ContainsSlice4)
data := []interface{}{"name", 12, true}

From(data).Contains("name").Result() // ===> true
From(data).Contains(12).Result()     // ===> true
From(data).Contains(true).Result()   // ===> true
Output:

Example (ContainsSlice5)
From("damian").Contains("an").Result() // ===> true
Output:

func (*Chainable) Count

func (g *Chainable) Count() IChainableNumberResult

Count get the length of `data`.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() int                  // ==> description: returns length of data
.ResultAndError() (int, error) // ==> description: returns length of data, and error object
.Error() error                 // ==> description: returns error object
.IsError() bool                // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (CountMap1)
data := map[string]interface{}{
	"name":   "jason",
	"age":    12,
	"isMale": true,
}
result := From(data).Count().Result()
fmt.Println(result)
// ===> 3
Output:

Example (CountSlice1)
data := []string{"damian", "grayson", "cassandra"}

result := From(data).Count().Result()
fmt.Println(result)
// ===> 3
Output:

func (*Chainable) CountBy

func (g *Chainable) CountBy(iteratee interface{}) IChainableNumberResult

CountBy get the length of `data` filtered by `iteratee`.

Parameters

This function requires single mandatory parameter:

iteratee interface{} // ==> type: `func(each anyType, i int)bool` or
                     //           `func(value anyType, key anyType, i int)bool`
                     //     description: the function invoked per iteration

Return values

Chain with these methods to get result:

.Result() int                  // ==> description: returns the result after operation
.ResultAndError() (int, error) // ==> description: returns the result after operation, and error object
.Error() error                 // ==> description: returns error object
.IsError() bool                // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (CountMap2)
data := map[string]interface{}{
	"name":   "jason",
	"age":    12,
	"isMale": true,
}

result := From(data).
	CountBy(func(val interface{}, key string) bool {
		return strings.Contains(strings.ToLower(key), "m")
	}).
	Result()
fmt.Println(result)
// ===> 2
Output:

Example (CountMap3)
data := map[string]interface{}{
	"name":   "jason",
	"age":    12,
	"isMale": true,
}

result := From(data).
	CountBy(func(val interface{}, key string, i int) bool {
		return strings.Contains(strings.ToLower(key), "m") && i > 1
	}).
	Result()
fmt.Println(result)
// ===> 1
Output:

Example (CountSlice2)
data := []string{"damian", "grayson", "cassandra"}

result := From(data).
	CountBy(func(each string) bool {
		return strings.Contains(each, "d")
	}).
	Result()
fmt.Println(result)
// ===> 2
Output:

Example (CountSlice3)
data := []string{"damian", "grayson", "cassandra"}

result := From(data).
	CountBy(func(each string, i int) bool {
		return len(each) > 6 && i > 1
	}).
	Result()

fmt.Println(result)
// ===> 1
Output:

func (*Chainable) Difference

func (g *Chainable) Difference(dataToCompare interface{}) IChainable

Difference function creates a slice of `data` that values not included in the other given slice. The order and references of result values are determined by the first slice.

Parameters

This function requires single mandatory parameter:

dataToCompare interface{} // ==> description: the slice to differentiate

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Difference1)
data := []int{1, 2, 3, 4, 4, 6, 7}
dataDiff := []int{2, 7}

result := From(data).Difference(dataDiff).Result()
fmt.Println(result)
// ===> []int{ 1, 3, 4, 4, 6 }
Output:

func (*Chainable) DifferenceMany

func (g *Chainable) DifferenceMany(datasToCompare ...interface{}) IChainable

DifferenceMany function creates a slice of `data` that values not included in the other given slices. The order and references of result values are determined by the first slice.

Parameters

This function requires optional variadic parameters:

datasToCompare1 interface{} // ==> description: the slice to differentiate
datasToCompare2 interface{} // ==> description: the slice to differentiate
datasToCompare3 interface{} // ==> description: the slice to differentiate
...

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Difference2)
data := []string{"a", "b", "b", "c", "d", "e", "f", "g", "h"}
dataDiff1 := []string{"b", "d"}
dataDiff2 := []string{"e", "f", "h"}

result := From(data).DifferenceMany(dataDiff1, dataDiff2).Result()
fmt.Println(result)
// ===> []string{ "a", "c", "g" }
Output:

Example (Difference3)
data := []float64{1.1, 1.11, 1.2, 2.3, 3.0, 3, 4.0, 4.00000, 4.000000001}
dataDiff1 := []float64{1.1, 3}
dataDiff2 := []float64{4.000000001}

result := From(data).DifferenceMany(dataDiff1, dataDiff2).Result()
fmt.Println(result)
// ===> []float64{ 1.11, 1.2, 2.3, 4, 4 }
Output:

func (*Chainable) Drop

func (g *Chainable) Drop(size int) IChainable

Drop function creates a slice of `data` with `n` elements dropped from the beginning.

Parameters

This function requires single mandatory parameter:

size int // ==> description: the number of elements to drop

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Drop1)
data := []int{1, 2, 3, 4, 4, 5, 6}
n := 1

result := From(data).Drop(n).Result()
fmt.Println(result)
// ===> []int{ 2, 3, 4, 4, 5, 6 }
Output:

Example (Drop2)
data := []string{"a", "b", "c", "d", "e", "f"}
n := 3

result := From(data).Drop(n).Result()
fmt.Println(result)
// ===> []string{ "d", "e", "f" }
Output:

func (*Chainable) DropRight

func (g *Chainable) DropRight(size int) IChainable

DropRight function creates a slice of `data` with `n` elements dropped from the end.

Parameters

This function requires single mandatory parameter:

size int // ==> description: the number of elements to drop

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (DropRight1)
data := []int{1, 2, 3, 4, 4, 5, 6}
n := 1

result := From(data).Drop(n).Result()
fmt.Println(result)
// ===> []int{ 1, 2, 3, 4, 4, 5 }
Output:

Example (DropRight2)
data := []string{"a", "b", "c", "d", "e", "f"}
n := 3

result := From(data).Drop(n).Result()
fmt.Println(result)
// ===> []string{ "a", "b", "c" }
Output:

func (*Chainable) Each

func (g *Chainable) Each(iteratee interface{}) IChainableNoReturnValueResult

Each iterates over elements of `data` and invokes `iteratee` for each element. Iteratee functions may exit iteration early by explicitly returning false

Parameters

This function requires single mandatory parameter:

iteratee interface{} // ==> type: `func(each anyType, i int)` or
                     //           `func(each anyType, i int)bool` or
                     //           `func(value anyType, key anyType, i int)` or
                     //           `func(value anyType, key anyType, i int)bool`
                     // ==> description: the function invoked per iteration.
                     //                  for slice, the 2nd argument represents index of each element, and it's optional.
                     //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                     //                  and both are optional.
                     //                  if return value is provided then the next iteration is controlled by returned value.
                     //                  `return true` will make the iteration continue, meanwhile `return false` will stop it

Return values

Chain with these methods to get result:

.Error() error  // ==> description: returns error object
.IsError() bool // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (EachMap1)
data := map[string]interface{}{
	"name":   "damian",
	"age":    17,
	"gender": "male",
}

err := From(data).
	Each(func(value interface{}, key string) {
		fmt.Printf("%s: %v \n", key, value)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachMap2)
data := map[string]interface{}{
	"name":   "damian",
	"age":    17,
	"gender": "male",
}

err := From(data).
	Each(func(value interface{}, key string, i int) {
		fmt.Printf("key: %s, value: %v, index: %d \n", key, value, i)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachSlice1)
data := []string{"damian", "grayson", "cassandra"}

err := From(data).
	Each(func(each string) {
		fmt.Println(each)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachSlice2)
data := []string{"damian", "grayson", "cassandra"}

err := From(data).
	Each(func(each string, i int) {
		fmt.Printf("element %d: %s \n", i, each)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachSlice3)
type Sample struct {
	Name string
	Age  int
}

data := []Sample{
	{Name: "damian", Age: 12},
	{Name: "grayson", Age: 10},
	{Name: "cassandra", Age: 11},
}

err := From(data).
	Each(func(each Sample) {
		fmt.Printf("name: %s, age: %d \n", each.Name, each.Age)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachSlice4)
data := []string{"damian", "grayson", "cassandra", "tim", "jason", "stephanie"}

err := From(data).
	Each(func(each string, i int) bool {
		if i > 3 { // will stop after fourth loop
			return false
		}

		fmt.Println(each)
		return true
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

func (*Chainable) EachRight

func (g *Chainable) EachRight(iteratee interface{}) IChainableNoReturnValueResult

EachRight iterates over elements of `data` from tail to head, and invokes `iteratee` for each element. Iteratee functions may exit iteration early by explicitly returning false

Parameters

This function requires single mandatory parameter:

iteratee interface{} // ==> type: `func(each anyType, i int)` or
                     //           `func(each anyType, i int)bool` or
                     //           `func(value anyType, key anyType, i int)` or
                     //           `func(value anyType, key anyType, i int)bool`
                     // ==> description: the function invoked per iteration.
                     //                  for slice, the 2nd argument represents index of each element, and it's optional.
                     //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                     //                  and both are optional.
                     //                  if return value is provided then the next iteration is controlled by returned value.
                     //                  `return true` will make the iteration continue, meanwhile `return false` will stop it

Return values

Chain with these methods to get result:

.Error() error  // ==> description: returns error object
.IsError() bool // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (EachRightMap1)
data := map[string]interface{}{
	"name":   "damian",
	"age":    17,
	"gender": "male",
}

err := From(data).
	EachRight(func(value interface{}, key string) {
		fmt.Printf("%s: %v \n", key, value)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachRightMap2)
data := map[string]interface{}{
	"name":   "damian",
	"age":    17,
	"gender": "male",
}

err := From(data).
	EachRight(func(value interface{}, key string, i int) {
		fmt.Printf("key: %s, value: %v, index: %d \n", key, value, i)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachRightSlice1)
data := []string{"damian", "grayson", "cassandra"}

err := From(data).
	EachRight(func(each string) {
		fmt.Println(each)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachRightSlice2)
data := []string{"damian", "grayson", "cassandra"}

err := From(data).
	EachRight(func(each string, i int) {
		fmt.Printf("element %d: %s \n", i, each)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachRightSlice3)
type Sample struct {
	Name string
	Age  int
}

data := []Sample{
	{Name: "damian", Age: 12},
	{Name: "grayson", Age: 10},
	{Name: "cassandra", Age: 11},
}

err := From(data).
	EachRight(func(each Sample) {
		fmt.Printf("name: %s, age: %d \n", each.Name, each.Age)
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

Example (EachRightSlice4)
data := []string{"damian", "grayson", "cassandra", "tim", "jason", "stephanie"}

err := From(data).
	EachRight(func(each string, i int) bool {
		if i > 3 { // will stop after fourth loop
			return false
		}

		fmt.Println(each)
		return true
	}).
	Error()
if err != nil {
	log.Fatal(err.Error())
}
Output:

func (*Chainable) Error

func (g *Chainable) Error() error

Error returns the error object

func (*Chainable) Exclude

func (g *Chainable) Exclude(itemToExclude interface{}) IChainable

Exclude function removes value from `data`.

Parameters

This function requires single mandatory parameter:

itemToExclude interface{} // ==> description: the item to exclude

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Exclude1)
data := []int{1, 2, 3, 4, 5, 6}
result := From(data).Exclude(3).Result()

fmt.Println(result)
// ===> []int{ 1, 2, 4, 5, 6 }
Output:

func (*Chainable) ExcludeAt

func (g *Chainable) ExcludeAt(indexOfItemToExclude int) IChainable

ExcludeAt function removes value by index from `data`.

Parameters

This function requires single mandatory parameter:

indexOfItemToExclude interface{} // ==> description: the index of item to exclude

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (ExcludeAt)
data := []float64{1.1, 2.1, 3.2, 4.2, 5.2, 6.3}

result := From(data).ExcludeAt(1).Result()

fmt.Println(result)
// ===> []float64{ 2.1, 3.2, 4.2, 5.2, 6.3 }
Output:

Example (ExcludeAtMany)
data := []float64{1.1, 2.1, 3.2, 4.2, 5.2, 6.3}

result := From(data).ExcludeAtMany(1, 3).Result()

fmt.Println(result)
// ===> []float64{ 1.1, 3.2, 5.2, 6.3 }
Output:

func (*Chainable) ExcludeAtMany

func (g *Chainable) ExcludeAtMany(indexesOfItemToExclude ...int) IChainable

ExcludeAtMany function removes value by index from `data`.

Parameters

This function requires optional variadic parameters:

indexOfItemToExclude1 interface{} // ==> description: the index of item to exclude
indexOfItemToExclude2 interface{} // ==> description: the index of item to exclude
indexOfItemToExclude3 interface{} // ==> description: the index of item to exclude
...

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

func (*Chainable) ExcludeMany

func (g *Chainable) ExcludeMany(itemsToExclude ...interface{}) IChainable

ExcludeMany function removes all given values from `data`.

Parameters

This function requires optional variadic parameters:

itemToExclude1 interface{} // ==> description: the item to exclude
itemToExclude2 interface{} // ==> description: the item to exclude
itemToExclude3 interface{} // ==> description: the item to exclude
...

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (ExcludeMany1)
data := []float64{1.1, 2.1, 3.2, 4.2, 5.2, 6.3}
result := From(data).ExcludeMany(2.1, 3.2, 6.3).Result()

fmt.Println(result)
// ===> []float64{ 1.1, 4.2, 5.2 }
Output:

Example (ExcludeMany2)
data := []string{"damian", "grayson", "cassandra", "tim", "tim", "jason", "stephanie"}
result := From(data).ExcludeMany("grayson", "tim").Result()

fmt.Println(result)
// ===> []string{ "damian", "cassandra", "jason", "stephanie" }
Output:

func (*Chainable) Fill

func (g *Chainable) Fill(value interface{}, args ...int) IChainable

Fill function fills elements of `data` with `value` from `start` up to, but not including, `end`.

Parameters

This function requires single mandatory parameter, `value`; and two other optional parameters:

value interface{} // ==> description: the value to fill slice with. This variable's data type must be same with slice's element data type
start int         // ==> optional
                  //     description: the start position
                  //     default value: 0
end int           // ==> optional
                  //     description: the end position
                  //     default value: len(data)

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Fill1)
data := []int{1, 2, 3, 4, 4, 5, 6}
replacement := 9

result := From(data).Fill(replacement).Result()

fmt.Println(result)
// ===> []int{ 9, 9, 9, 9, 9, 9, 9 }
Output:

Example (Fill2)
data := []string{"grayson", "jason", "tim", "damian"}
replacement := "alfred"
start := 2

result := From(data).Fill(replacement, start).Result()

fmt.Println(result)
// ===> []int{ "grayson", "jason", "alfred", "alfred" }
Output:

Example (Fill3)
data := []float64{1, 2.2, 3.0002, 4, 4, 5.12, 6}
replacement := float64(9)
start, end := 3, 5

result := From(data).Fill(replacement, start, end).Result()

fmt.Println(result)
// ===> []float64{ 1, 2.2, 3.0002, 9, 9, 5.12, 6 }
Output:

func (*Chainable) Filter

func (g *Chainable) Filter(predicate interface{}) IChainable

Filter function iterates over elements of slice or struct object or map, returning an array of all elements predicate returns truthy for.

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)bool` or
                      //           `func(value anyType, key anyType, i int)bool`
                      // ==> description: the function invoked per iteration.
                      //                  for slice, the 2nd argument represents index of each element, and it's optional.
                      //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                      //                  and both are optional.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (FilterMap)
data := map[string]int{
	"clean code":       10000,
	"rework":           12000,
	"detective comics": 11500,
}

result := From(data).
	Filter(func(value int, key string) bool {
		return value > 11000
	}).
	Result()

fmt.Println(result)
/*
	  map[string]int{
		"rework":           12000,
		"detective comics": 11500,
	  }
*/}
*/
Output:

Example (FilterSlice)
type Sample struct {
	EbookName      string
	DailyDownloads int
}

data := []Sample{
	{EbookName: "clean code", DailyDownloads: 10000},
	{EbookName: "rework", DailyDownloads: 12000},
	{EbookName: "detective comics", DailyDownloads: 11500},
}

result := From(data).
	Filter(func(each Sample) bool {
		return each.DailyDownloads > 11000
	}).
	Result()

fmt.Println(result)
/*
	  []Sample{
		{ EbookName: "rework", DailyDownloads: 12000 },
		{ EbookName: "detective comics", DailyDownloads: 11500 },
	  }
*/}
*/
Output:

func (*Chainable) Find

func (g *Chainable) Find(predicate interface{}, args ...int) IChainable

Find function iterates over elements of collection, returning the first element predicate returns truthy for.

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)bool` or
                      //           `func(value anyType, key anyType, i int)bool`
                      // ==> description: the function invoked per iteration.
                      //                  for slice, the 2nd argument represents index of each element, and it's optional.
                      //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                      //                  and both are optional.
fromIndex int         // ==> optional
                      //     description: The index to search from
                      //     default value: 0

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Find1)
type Sample struct {
	EbookName      string
	DailyDownloads int
}

data := []Sample{
	{EbookName: "clean code", DailyDownloads: 10000},
	{EbookName: "rework", DailyDownloads: 12000},
	{EbookName: "detective comics", DailyDownloads: 11500},
}

result := From(data).
	Find(func(each Sample) bool {
		return each.EbookName == "rework"
	}).
	Result()

fmt.Println(result)
// ===> Sample { EbookName: "rework", DailyDownloads: 12000 }
Output:

Example (Find2)
data := []string{"clean code", "rework", "detective comics"}

result := From(data).
	Find(func(each string, i int) bool {
		return strings.Contains(each, "co")
	}, 1).
	Result()

fmt.Println(result)
// ===> "detective comics"
Output:

func (*Chainable) FindIndex

func (g *Chainable) FindIndex(predicate interface{}, args ...int) IChainable

FindIndex function iterates over elements of collection, returning the index of first element predicate returns truthy for.

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)bool` or
                      //           `func(value anyType, key anyType, i int)bool`
                      // ==> description: the function invoked per iteration.
                      //                  for slice, the 2nd argument represents index of each element, and it's optional.
                      //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                      //                  and both are optional.
fromIndex int         // ==> optional
                      //     description: The index to search from
                      //     default value: 0

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (FindIndex1)
data := []string{"damian", "grayson", "cass", "tim", "tim", "jason", "steph"}
predicate := func(each string) bool {
	return each == "tim"
}

result := From(data).
	FindIndex(predicate).
	Result()

fmt.Println(result)
// ===> 3
Output:

Example (FindIndex2)
data := []int{-2, -1, 0, 1, 2}

result := From(data).
	FindIndex(func(each int) bool {
		return each == 4
	}).
	Result()

fmt.Println(result)
// ===> -1
Output:

Example (FindIndex3)
data := []float64{1, 1.1, 1.2, 1.200001, 1.2000000001, 1.3}

result := From(data).
	FindIndex(func(each float64) bool {
		return each == 1.2000000001
	}).
	Result()

fmt.Println(result)
// ===> 4
Output:

Example (FindIndex4)
data := []int{1, 2, 3, 3, 4, 5}
predicate := func(each int) bool {
	return each == 3
}
fromIndex := 2

result := From(data).
	FindIndex(predicate, fromIndex).
	Result()

fmt.Println(result)
// ===> 2
Output:

Example (FindIndex5)
data := []int{1, 2, 3, 3, 4, 5}
predicate := func(each int) bool {
	return each == 3
}
fromIndex := 3

result := From(data).
	FindIndex(predicate, fromIndex).
	Result()

fmt.Println(result)
// ===> 3
Output:

func (*Chainable) FindLast

func (g *Chainable) FindLast(predicate interface{}, args ...int) IChainable

FindLast function iterates over elements from tail to head, returning the first element predicate returns truthy for.

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)bool` or
                      //           `func(value anyType, key anyType, i int)bool`
                      // ==> description: the function invoked per iteration.
                      //                  for slice, the 2nd argument represents index of each element, and it's optional.
                      //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                      //                  and both are optional.
fromIndex int         // ==> optional
                      //     description: The index to search from
                      //     default value: len(data)-1

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (FindLast1)
type Sample struct {
	EbookName      string
	DailyDownloads int
}

data := []Sample{
	{EbookName: "clean code", DailyDownloads: 10000},
	{EbookName: "rework", DailyDownloads: 12000},
	{EbookName: "detective comics", DailyDownloads: 11500},
}

result := From(data).
	FindLast(func(each Sample) bool {
		return strings.Contains(each.EbookName, "co")
	}).
	Result()

fmt.Println(result)
// ===> Sample { EbookName: "detective comics", DailyDownloads: 11500 }
Output:

Example (FindLast2)
data := []string{"clean code", "rework", "detective comics", "coco"}

result := From(data).
	FindLast(func(each string, i int) bool {
		return strings.Contains(each, "co")
	}, 2).
	Result()

fmt.Println(result)
// ===> "detective comics"
Output:

Example (FindLast3)
data := []string{"clean code", "rework", "detective comics", "coco"}

result := From(data).
	FindLast(func(each string, i int) bool {
		return strings.Contains(each, "co")
	}, 3).
	Result()

fmt.Println(result)
// ===> "coco"
Output:

func (*Chainable) FindLastIndex

func (g *Chainable) FindLastIndex(predicate interface{}, args ...int) IChainable

FindLastIndex function iterates over elements from tail to head, returning the index of first element predicate returns truthy for.

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)bool` or
                      //           `func(value anyType, key anyType, i int)bool`
                      // ==> description: the function invoked per iteration.
                      //                  for slice, the 2nd argument represents index of each element, and it's optional.
                      //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                      //                  and both are optional.
fromIndex int         // ==> optional
                      //     description: The index to search from
                      //     default value: len(data)-1

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (FindLastIndex1)
data := []string{"damian", "grayson", "cass", "tim", "tim", "jason", "steph"}

result := From(data).
	FindLastIndex(func(each string) bool {
		return each == "tim"
	}).
	Result()

fmt.Println(result)
// ===> 4
Output:

Example (FindLastIndex2)
data := []int{1, 2, 2, 3, 3, 4, 5}
predicate := func(each int) bool {
	return each == 3
}
fromIndex := 4

result := From(data).
	FindLastIndex(predicate, fromIndex).
	Result()

fmt.Println(result)
// ===> 4
Output:

Example (FindLastIndex3)
data := []int{1, 2, 3, 3, 4, 5}
predicate := func(each int) bool {
	return each == 3
}
fromIndex := 3

result := From(data).
	FindLastIndex(predicate, fromIndex).
	Result()

fmt.Println(result)
// ===> 3
Output:

Example (FindLastIndex4)
data := []int{1, 2, 3, 3, 4, 5}
predicate := func(each int) bool {
	return each == 3
}
fromIndex := 2

result := From(data).
	FindLastIndex(predicate, fromIndex).
	Result()

fmt.Println(result)
// ===> -1
Output:

func (*Chainable) First

func (g *Chainable) First() IChainable

First function gets the first element of `data`.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (First1)
data := []string{"damian", "grayson", "cassandra"}
result := From(data).First().Result()

fmt.Println(result)
// ===> "damian"
Output:

Example (First2)
data := []string{}
result := From(data).First().Result()

fmt.Println(result)
// ===> nil
Output:

func (*Chainable) FromPairs

func (g *Chainable) FromPairs() IChainable

FromPairs function returns an object composed from key-value `data`.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (FromPairs1)
data := []interface{}{
	[]interface{}{"a", 1},
	[]interface{}{"b", 2},
}

result := From(data).FromPairs().Result()

fmt.Println(result)
/*
	  map[interface{}]interface{}{
		"a": 1,
		"b": 2,
	  }
*/}
*/
Output:

Example (FromPairs2)
data := []interface{}{
	[]interface{}{true, []int{1, 2, 3}},
	[]interface{}{false, []string{"damian", "grayson"}},
}

result := From(data).FromPairs().Result()

fmt.Println(result)
/*
	map[interface{}]interface{}{
	  true: []int{ 1, 2, 3 },
	  false: []string{ "damian", "grayson" },
	}
*/}
*/
Output:

func (*Chainable) GroupBy

func (g *Chainable) GroupBy(predicate interface{}) IChainable

GroupBy function creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key.

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)<any type>`
                      // ==> description: the function invoked per iteration.
                      //                  the 2nd argument represents index of each element, and it's optional.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (GroupBy1)
type Sample struct {
	Ebook    string
	Category string
}

data := []Sample{
	{Ebook: "clean code", Category: "productivity"},
	{Ebook: "rework", Category: "productivity"},
	{Ebook: "detective comics", Category: "comics"},
	{Ebook: "injustice 2", Category: "comics"},
	{Ebook: "dragon ball", Category: "manga"},
	{Ebook: "one piece", Category: "manga"},
}

result := From(data).
	GroupBy(func(each Sample) string {
		return each.Category
	}).
	Result()

fmt.Println(result)
/*
	  map[string][]main.Sample {
		"productivity": []main.Sample {
		  { Ebook: "clean code", Category: "productivity" },
		  { Ebook: "rework", Category: "productivity" },
		},
		"comics":       []main.Sample {
		  { Ebook: "detective comics", Category: "comics"},
		  { Ebook: "injustice 2", Category: "comics"},
		},
		"manga":        []main.Sample {
		  { Ebook: "dragon ball", Category: "manga" },
		  { Ebook: "one piece", Category: "manga"},
		},
	  }
*/			},
	  }
*/
Output:

Example (GroupBy2)
data := []int{1, 2, 3, 5, 6, 4, 2, 5, 2}

result := From(data).
	GroupBy(func(each int) int {
		return each
	}).
	Result()

fmt.Println(result)
/*
   map[int][]int{
     5: []int{ 5, 5 },
     6: []int{ 6 },
     4: []int{ 4 },
     1: []int{ 1 },
     2: []int{ 2, 2, 2 },
     3: []int{ 3 },
   }
*/	   }
*/
Output:

func (*Chainable) IndexOf

func (g *Chainable) IndexOf(search interface{}, args ...int) IChainableNumberResult

IndexOf function gets the index at which the first occurrence of `search` is found in `data`. If `fromIndex` is negative, it's used as the offset from the end of `data`.

Parameters

This function requires single mandatory parameter:

search interface{} // ==> description: the value to search for.
fromIndex int      // ==> optional
                   //     description: The index to search from
                   //     default value: 0

Return values

Chain with these methods to get result:

.Result() int                  // ==> description: return the index of found element
.ResultAndError() (int, error) // ==> description: return the index of found element, and error object
.Error() error                 // ==> description: returns error object
.IsError() bool                // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (IndexOf1)
data := []string{"damian", "grayson", "cass", "tim", "tim", "jason", "steph"}

From(data).IndexOf("duke").Result()    // ===> -1
From(data).IndexOf("tim").Result()     // ===> 3
From(data).IndexOf("tim", 4).Result()  // ===> 4
From(data).IndexOf("tim", -4).Result() // ===> 3
From(data).IndexOf("tim", -3).Result() // ===> 4
From(data).IndexOf("tim", -2).Result() // ===> -1
Output:

Example (IndexOf2)
data := []float64{2.1, 2.2, 3, 3.00000, 3.1, 3.9, 3.95}

From(data).IndexOf(2.2).Result()           // ===> 1
From(data).IndexOf(3).Result()             // ===> -1
From(data).IndexOf(float64(3)).Result()    // ===> 2 (because 3 is detected as int32, not float64)
From(data).IndexOf(float64(3), 2).Result() // ===> 2
From(data).IndexOf(float64(3), 3).Result() // ===> 3
Output:

Example (IndexOf3)
data := []interface{}{"jason", 24, true}

From(data).IndexOf(24).Result()     // ===> 1
From(data).IndexOf(24, -1).Result() // ===> -1
Output:

func (*Chainable) Initial

func (g *Chainable) Initial() IChainable

Initial function gets all but the last element of `data`.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Initial1)
data := []string{"damian", "grayson", "cassandra"}

result := From(data).Initial().Result()

fmt.Println(result)
// ===> []string{ "damian", "grayson" }
Output:

Example (Initial2)
data := []int{1, 2, 3, 4, 5}

result := From(data).Initial().Result()

fmt.Println(result)
// ===> []int{ 1, 2, 3, 4 }
Output:

Example (Initial3)
data := []map[string]string{{"name": "jason"}}

result := From(data).Initial().Result()

fmt.Println(result)
// ===> []map[string]string{}
Output:

Example (Initial4)
data := []float64{}

result := From(data).Initial().Result()

fmt.Println(result)
// ===> []float64{}
Output:

func (*Chainable) Intersection

func (g *Chainable) Intersection(dataIntersect interface{}) IChainable

Intersection function creates a slice of unique values that are included in all given slice. The order and references of result values are determined by the first slice.

Parameters

This function requires single mandatory parameter:

dataToIntersect interface{} // ==> description: the slice to intersect

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Intersection1)
result := From([]string{"damian", "grayson", "cassandra", "tim", "tim", "jason"}).
	Intersection([]string{"cassandra", "tim", "jason"}).
	Result()

fmt.Println(result)
// ===> []string{ "cassandra", "tim", "jason" }
Output:

Example (Intersection2)
result := From([]float64{0.8, 0.8001, 0.999, 1, 1.0, 1.000001, 1.1000000, 1.1001, 1.2, 1.33, 1.4}).
	IntersectionMany(
		[]float64{0.8, 0.8001, 0.999, 1, 1.0, 1.000001, 1.1000000, 1.2, 1.33},
		[]float64{1.1000000, 1.2, 0.8001, 0.999, 1.33, 1, 1.0, 1.000001},
		[]float64{1.2, 0.8001, 0.999, 1.33, 1.000092},
		[]float64{0.8001, 0.999, 1.33, 1.400001},
	).
	Result()

fmt.Println(result)
// ===> []float64{ 0.8001, 0.999, 1.33 }
Output:

func (*Chainable) IntersectionMany

func (g *Chainable) IntersectionMany(dataToIntersects ...interface{}) IChainable

IntersectionMany function creates a slice of unique values that are included in all given slices. The order and references of result values are determined by the first slice.

Parameters

This function requires optional variadic parameters:

dataToIntersect1 interface{} // ==> description: the slice to intersect
dataToIntersect2 interface{} // ==> description: the slice to intersect
dataToIntersect3 interface{} // ==> description: the slice to intersect
...

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

func (*Chainable) IsError

func (g *Chainable) IsError() bool

IsError `true` on error, otherwise `false`

func (*Chainable) Join

func (g *Chainable) Join(separator string) IChainableStringResult

Join function converts all elements in `data` into a string separated by `separator`.

Parameters

This function requires single mandatory parameter:

separator string // ==> description: the element joiner

Return values

Chain with these methods to get result:

.Result() string                  // ==> description: returns the result after operation
.ResultAndError() (string, error) // ==> description: returns the result after operation, and error object
.Error() error                    // ==> description: returns error object
.IsError() bool                   // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Join1)
data := []string{"damian", "grayson", "cassandra"}
separator := " - "

result := From(data).Join(separator).Result()

fmt.Println(result)
// ===> "damian - grayson - cassandra"
Output:

Example (Join2)
data := []int{1, 2, 3, 4}
separator := ", "

result := From(data).Join(separator).Result()

fmt.Println(result)
// ===> "1, 2, 3, 4"
Output:

func (*Chainable) KeyBy

func (g *Chainable) KeyBy(predicate interface{}) IChainable

KeyBy function creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the last element responsible for generating the key.

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)<any type>` or
                      //           `func(value anyType, key anyType, i int)<any type>`
                      // ==> description: the function invoked per iteration.
                      //                  for slice, the 2nd argument represents index of each element, and it's optional.
                      //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                      //                  and both are optional.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (KeyBy)
type HashMap map[string]string

data := []HashMap{
	{"name": "grayson", "hobby": "helping people"},
	{"name": "jason", "hobby": "punching people"},
	{"name": "tim", "hobby": "stay awake all the time"},
	{"name": "damian", "hobby": "getting angry"},
}

result := From(data).
	KeyBy(func(each HashMap) string {
		return each["name"]
	}).
	Result()

fmt.Println(result)
/*
   map[string]main.HashMap {
     "grayson": main.HashMap{ "hobby": "helping people", "name": "grayson" },
     "jason":   main.HashMap{ "name": "jason", "hobby": "punching people" },
     "tim":     main.HashMap{ "name": "tim", "hobby": "stay awake all the time" },
     "damian":  main.HashMap{ "name": "damian", "hobby": "getting angry" },
   }
*/  }
*/
Output:

func (*Chainable) Last

func (g *Chainable) Last() IChainable

Last function gets the last element of `data`.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Last1)
data := []string{"damian", "grayson", "cassandra"}

result := From(data).Last().Result()

fmt.Println(result)
// ===> "cassandra"
Output:

Example (Last2)
data := []int{1}

result := From(data).Last().Result()

fmt.Println(result)
// ===> 1
Output:

Example (Last3)
data := []string{}

result := From(data).Last().Result()

fmt.Println(result)
// ===> nil
Output:

func (*Chainable) LastErrorOperation

func (g *Chainable) LastErrorOperation() Operation

LastErrorOperation return last error operation

func (*Chainable) LastIndexOf

func (g *Chainable) LastIndexOf(search interface{}, args ...int) IChainableNumberResult

LastIndexOf function iterates the element from tail to head, then return the index at which the first occurrence of `search` is found in `data`. If `fromIndex` is negative, it's used as the offset from the end of `data`.

Parameters

This function requires single mandatory parameter:

search interface{} // ==> description: the value to search for.
fromIndex int      // ==> optional
                   //     description: The index to search from
                   //     default value: len(data)-1

Return values

Chain with these methods to get result:

.Result() int                  // ==> description: return the index of found element
.ResultAndError() (int, error) // ==> description: return the index of found element, and error object
.Error() error                 // ==> description: returns error object
.IsError() bool                // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (LastIndexOf1)
data := []string{"damian", "grayson", "cass", "tim", "tim", "jason", "steph"}

From(data).LastIndexOf("duke").Result()    // ===> -1
From(data).LastIndexOf("tim").Result()     // ===> 4
From(data).LastIndexOf("tim", 4).Result()  // ===> 4
From(data).LastIndexOf("tim", -4).Result() // ===> 3
From(data).LastIndexOf("tim", -3).Result() // ===> 4
From(data).LastIndexOf("tim", -2).Result() // ===> 4
Output:

Example (LastIndexOf2)
data := []float64{2.1, 2.2, 3, 3.00000, 3.1, 3.9, 3.95}

From(data).LastIndexOf(2.2).Result()           // ===> 1
From(data).LastIndexOf(3).Result()             // ===> -1 (because 3 is detected as int32, not float64)
From(data).LastIndexOf(float64(3)).Result()    // ===> 3
From(data).LastIndexOf(float64(3), 2).Result() // ===> 2
From(data).LastIndexOf(float64(3), 3).Result() // ===> 3
Output:

Example (LastIndexOf3)
data := []interface{}{"jason", 24, true}

From(data).LastIndexOf(24).Result()     // ===> 1
From(data).LastIndexOf(24, -1).Result() // ===> 1
Output:

func (*Chainable) LastOperation

func (g *Chainable) LastOperation() Operation

LastOperation return last operation

func (*Chainable) LastSuccessOperation

func (g *Chainable) LastSuccessOperation() Operation

LastSuccessOperation return last success operation

func (*Chainable) Map

func (g *Chainable) Map(callback interface{}) IChainable

Map function creates an array of values by running each element in `data` thru iteratee.

Parameters

This function requires single mandatory parameter:

callback interface{} // ==> type: `func(each anyType, i int)<any type>` or
                     //           `func(value anyType, key anyType, i int)<any type>`
                     // ==> description: the function invoked per iteration.
                     //                  for slice, the 2nd argument represents index of each element, and it's optional.
                     //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                     //                  and both are optional.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Map1)
type Sample struct {
	EbookName      string
	DailyDownloads int
}

data := []Sample{
	{EbookName: "clean code", DailyDownloads: 10000},
	{EbookName: "rework", DailyDownloads: 12000},
	{EbookName: "detective comics", DailyDownloads: 11500},
}

result := From(data).
	Map(func(each Sample, i int) string {
		return each.EbookName
	}).
	Result()

fmt.Println(result)
// ===> []string{ "clean code", "rework", "detective comics" }
Output:

Example (Map2)
type SampleOne struct {
	EbookName      string
	DailyDownloads int
	IsActive       bool
}

type SampleTwo struct {
	Ebook                string
	DownloadsInThousands float32
}

data := []SampleOne{
	{EbookName: "clean code", DailyDownloads: 10000, IsActive: true},
	{EbookName: "rework", DailyDownloads: 12000, IsActive: false},
	{EbookName: "detective comics", DailyDownloads: 11500, IsActive: true},
}

result := From(data).
	Map(func(each SampleOne, i int) SampleTwo {
		ebook := each.EbookName
		if !each.IsActive {
			ebook = fmt.Sprintf("%s (inactive)", each.EbookName)
		}

		downloadsInThousands := float32(each.DailyDownloads) / float32(1000)

		return SampleTwo{Ebook: ebook, DownloadsInThousands: downloadsInThousands}
	}).
	Result()

fmt.Println(result)
/*

	  []SampleTwo {
		{ Ebook: "clean code", DownloadsInThousands: 10 },
		{ Ebook: "rework (inactive)", DownloadsInThousands: 12 },
		{ Ebook: "detective comics", DownloadsInThousands: 11.5 },
	  }

*/}

*/
Output:

func (*Chainable) Nth

func (g *Chainable) Nth(index int) IChainable

Nth function gets the element at index `n` of `data`. If `n` is negative, the nth element from the end is returned.

Parameters

This function requires single mandatory parameter:

index int // ==> description: the index of the element to return

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Nth1)
data := []string{"grayson", "jason", "tim", "damian"}

From(data).Nth(1).Result()  // ===> "jason"
From(data).Nth(2).Result()  // ===> "tim"
From(data).Nth(-1).Result() // ===> "damian"
Output:

Example (Nth2)
data := []int{1, 2, 3, 4, 5}
From(data).Nth(4).Result() // ===> 5
Output:

func (*Chainable) OrderBy

func (g *Chainable) OrderBy(predicate interface{}, args ...bool) IChainable

OrderBy sort slices. If orders is unspecified, all values are sorted in ascending order. Otherwise, specify an order of "desc" for descending or "asc" for ascending sort order of corresponding values. The algorithm used is merge sort, as per savigo's post on https://sagivo.com/go-sort-faster-4869bdabc670

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)<any type>` or
                      //           `func(value anyType, key anyType, i int)<any type>`
                      // ==> description: the function invoked per iteration.
                      //                  for slice, the 2nd argument represents index of each element, and it's optional.
                      //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                      //                  and both are optional.
isAscending bool      // ==> optional
                      //     description: the sort order. `true` for ascending, and `false` for descending.
                      //     default value: true
isAsync bool          // ==> optional
                      //     description: concurrent sort. set to `true` to enable pararel sorting (faster for certain data structure)
                      //     default value: false

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (OrderBy1)
type HashMap map[string]string

data := []HashMap{
	{"name": "tim", "hobby": "stay awake all the time"},
	{"name": "grayson", "hobby": "helping people"},
	{"name": "damian", "hobby": "getting angry"},
	{"name": "jason", "hobby": "punching people"},
}

result := From(data).
	OrderBy(func(each HashMap) string {
		return each["name"]
	}).
	Result()

fmt.Println(result)
/*
   []main.HashMap{
     { "name": "damian", "hobby": "getting angry" },
     { "name": "grayson", "hobby": "helping people" },
     { "name": "jason", "hobby": "punching people" },
     { "name": "tim", "hobby": "stay awake all the time" },
   }
*/  }
*/
Output:

Example (OrderBy2)
type HashMap map[string]interface{}

data := []HashMap{
	{"name": "tim", "hobby": "stay awake all the time", "age": 20},
	{"name": "grayson", "hobby": "helping people", "age": 24},
	{"name": "damian", "hobby": "getting angry", "age": 17},
	{"name": "jason", "hobby": "punching people", "age": 22},
}

result := From(data).
	OrderBy(func(each HashMap) int {
		return each["age"].(int)
	}).
	Result()

fmt.Println(result)
/*
	[]main.HashMap{
	  { "age": 17, "hobby": "getting angry", "name": "damian" },
	  { "age": 20, "name": "tim", "hobby": "stay awake all the time" },
	  { "age": 22, "name": "jason", "hobby": "punching people" },
	  { "age": 24, "name": "grayson", "hobby": "helping people" },
	}
*/		}
*/
Output:

Example (OrderBy3)
type HashMap map[string]interface{}

data := []HashMap{
	{"name": "tim", "hobby": "stay awake all the time", "age": 20},
	{"name": "grayson", "hobby": "helping people", "age": 24},
	{"name": "damian", "hobby": "getting angry", "age": 17},
	{"name": "jason", "hobby": "punching people", "age": 22},
}

result := From(data).
	OrderBy(func(each HashMap) int {
		return each["age"].(int)
	}, false).
	Result()

fmt.Println(result)
/*
   []main.HashMap{
     { "age": 24, "name": "grayson", "hobby": "helping people" },
     { "age": 22, "name": "jason", "hobby": "punching people" },
     { "age": 20, "name": "tim", "hobby": "stay awake all the time" },
     { "age": 17, "name": "damian", "hobby": "getting angry" },
   }
*/  }
*/
Output:

Example (OrderBy4)
type HashMap map[string]interface{}

data := []HashMap{
	{"name": "tim", "hobby": "stay awake all the time", "age": 20},
	{"name": "grayson", "hobby": "helping people", "age": 24},
	{"name": "damian", "hobby": "getting angry", "age": 17},
	{"name": "jason", "hobby": "punching people", "age": 22},
}

result := From(data).
	OrderBy(func(each HashMap) int {
		return each["age"].(int)
	}, true, false).
	Result()

fmt.Println(result)
/*
   []main.HashMap{
     { "age": 17, "name": "damian", "hobby": "getting angry" },
     { "age": 20, "name": "tim", "hobby": "stay awake all the time" },
     { "age": 22, "name": "jason", "hobby": "punching people" },
     { "age": 24, "name": "grayson", "hobby": "helping people" },
   }
*/  }
*/
Output:

func (*Chainable) Partition

func (g *Chainable) Partition(callback interface{}) IChainableTwoReturnValueResult

Partition function creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for, the second of which contains elements predicate returns falsey for. The predicate is invoked with one argument: (value).

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)bool`
                      // ==> description: the function invoked per iteration.
                      //                  the 2nd argument represents index of each element, and it's optional.
                      //                  and both are optional.

Return values

Chain with these methods to get result:

.ResultTruthy() interface{}                         // ==> description: return slice of elements which predicate returns truthy for
.ResultFalsey() interface{}                         // ==> description: return slice of elements which predicate returns falsey for
.ResultAndError() (interface{}, interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                                      // ==> description: returns error object
.IsError() bool                                     // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Partition)
type HashMap map[string]interface{}

data := []HashMap{
	{"name": "grayson", "isMale": true},
	{"name": "jason", "isMale": true},
	{"name": "barbara", "isMale": false},
	{"name": "tim", "isMale": true},
	{"name": "cassandra", "isMale": false},
	{"name": "stephanie", "isMale": false},
	{"name": "damian", "isMale": true},
	{"name": "duke", "isMale": true},
}

resultTruthy, resultFalsey, err := From(data).
	Partition(func(each HashMap) bool {
		return each["isMale"].(bool)
	}).
	ResultAndError()
if err != nil {
	log.Fatal(err.Error())
}

fmt.Printf("%#v \n", resultTruthy)
/*
   []HashMap {
     { "name": "grayson", "isMale": true },
     { "name": "jason", "isMale": true },
     { "name": "tim", "isMale": true },
     { "name": "damian", "isMale": true },
     { "name": "duke", "isMale": true },
   }
*/   }
*/

fmt.Printf("%#v \n", resultFalsey)
/*
   []HashMap {
     { "name": "barbara", "isMale": false },
     { "name": "cassandra", "isMale": false },
     { "name": "stephanie", "isMale": false },
   }
*/ }
*/
Output:

func (*Chainable) Reduce

func (g *Chainable) Reduce(iteratee, initial interface{}) IChainable

Reduce function reduces collection to a value which is the accumulated result of running each element in collection thru iteratee, where each successive invocation is supplied the return value of the previous. If accumulator is not given, the first element of collection is used as the initial value.

Parameters

This function require two mandatory parameters:

iteratee interface{} // ==> type: `func(accumulator <any type>, each anyType, i int)<any type>` or
                     //           `func(accumulator <any type>, value anyType, key anyType, i int)<any type>`
                     // ==> description: the function invoked per iteration.
                     //                  the 1st argument is the accumulator. at first the value is coming from `initial`
                     //                  for slice, the 3rd argument represents index of each element, and it's optional.
                     //                  for struct object/map, the 3rd and 4th arguments represent key and index of each item respectively,
                     //                  and both are optional.
initial interface{}  // ==> description: the initial value.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (ReduceMap1)
type HashMap map[string]interface{}

data := HashMap{
	"name":   "grayson",
	"age":    21,
	"isMale": true,
}

result := From(data).
	Reduce(func(accumulator string, value interface{}, key string) string {
		if accumulator == "" {
			accumulator = fmt.Sprintf("%s: %v", key, value)
		} else {
			accumulator = fmt.Sprintf("%s, %s: %v", accumulator, key, value)
		}

		return accumulator
	}, "").
	Result()

fmt.Println(result)
// ===> "name: grayson, age: 21, isMale: true"
Output:

Example (ReduceSlice1)
data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

result := From(data).
	Reduce(func(accumulator, each int) int {
		return accumulator + each
	}, 0).
	Result()

fmt.Println(result)
// ===> 55
Output:

Example (ReduceSlice2)
type HashMap map[string]interface{}

data := [][]interface{}{
	{"name", "grayson"},
	{"age", 21},
	{"isMale", true},
}

result := From(data).
	Reduce(func(accumulator HashMap, each []interface{}, i int) HashMap {
		accumulator[each[0].(string)] = each[1]
		return accumulator
	}, HashMap{}).
	Result()

fmt.Println(result)
/*
   HashMap {
     "name":   "grayson",
     "age":    21,
     "isMale": true,
   }
*/ }
*/
Output:

func (*Chainable) Reject

func (g *Chainable) Reject(predicate interface{}) IChainable

Reject function iterates over elements of slice or struct object or map, returning an array of all elements predicate returns FALSEY for.

Parameters

This function requires single mandatory parameter:

predicate interface{} // ==> type: `func(each anyType, i int)bool` or
                      //           `func(value anyType, key anyType, i int)bool`
                      // ==> description: the function invoked per iteration.
                      //                  for slice, the 2nd argument represents index of each element, and it's optional.
                      //                  for struct object/map, the 2nd and 3rd arguments represent key and index of each item respectively,
                      //                  and both are optional.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (RejectMap)
data := map[string]int{
	"clean code":       10000,
	"rework":           12000,
	"detective comics": 11500,
}

result := From(data).Reject(func(value int, key string) bool {
	return value > 11000
}).Result()

fmt.Println(result)
// ===> map[string]int{ "clean code": 10000 }
Output:

Example (RejectSlice)
type Book struct {
	EbookName      string
	DailyDownloads int
}

data := []Book{
	{EbookName: "clean code", DailyDownloads: 10000},
	{EbookName: "rework", DailyDownloads: 12000},
	{EbookName: "detective comics", DailyDownloads: 11500},
}

result := From(data).Reject(func(each Book) bool {
	return each.DailyDownloads > 11000
}).Result()

fmt.Println(result)
/*
	  []Book{
		{ EbookName: "clean code", DailyDownloads: 10000 },
	  }
*/
*/
Output:

func (*Chainable) Result

func (g *Chainable) Result() interface{}

Result returns the result after operation

func (*Chainable) ResultAndError

func (g *Chainable) ResultAndError() (interface{}, error)

ResultAndError returns the result after operation, and error object

func (*Chainable) Reverse

func (g *Chainable) Reverse() IChainable

Reverse function reverses `data` so that the first element becomes the last, the second element becomes the second to last, and so on.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Reverse1)
data := []string{"jason", "damian", "grayson", "tim"}
result := From(data).Reverse().Result()

fmt.Println(result)
// ===> []string{ "tim", "grayson", "damian", "jason" }
Output:

Example (Reverse2)
data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
result := From(data).Reverse().Result()

fmt.Println(result)
// ===> []int{ 9, 8, 7, 6, 5, 4, 3, 2, 1 }
Output:

func (*Chainable) Sample

func (g *Chainable) Sample() IChainable

Sample function gets a random element from `data`.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Sample)
type Book struct {
	EbookName      string
	DailyDownloads int
}

data := []Book{
	{EbookName: "clean code", DailyDownloads: 10000},
	{EbookName: "rework", DailyDownloads: 12000},
	{EbookName: "detective comics", DailyDownloads: 11500},
}

result := From(data).Sample().Result()

fmt.Println(result)
/*
	  the result can be this:
		{ EbookName: "clean code", DailyDownloads: 10000 },

	  this:
		{ EbookName: "rework", DailyDownloads: 12000 },

	  or this:
		{ EbookName: "detective comics", DailyDownloads: 11500 },
*/ },
*/
Output:

func (*Chainable) SampleSize

func (g *Chainable) SampleSize(take int) IChainable

SampleSize function gets slice of random elements from `data`.

Parameters

This function requires single mandatory parameter:

take int // ==> description: the length of each chunk

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (SampleSize)
type Book struct {
	EbookName      string
	DailyDownloads int
}

data := []Book{
	{EbookName: "clean code", DailyDownloads: 10000},
	{EbookName: "rework", DailyDownloads: 12000},
	{EbookName: "detective comics", DailyDownloads: 11500},
}

result := From(data).SampleSize(2).Result()

fmt.Println(result)
/*
	  the result can be this:
		[]Book{
		  { EbookName: "clean code", DailyDownloads: 10000 },
		  { EbookName: "rework", DailyDownloads: 12000 },
		}

	  this:
		[]Book{
		  { EbookName: "rework", DailyDownloads: 12000 },
		  { EbookName: "detective comics", DailyDownloads: 11500 },
		}

	  or this:
		[]Book{
		  { EbookName: "clean code", DailyDownloads: 10000 },
		  { EbookName: "detective comics", DailyDownloads: 11500 },
		}
*/1500 },
		}
*/
Output:

func (*Chainable) Shuffle

func (g *Chainable) Shuffle() IChainable

Shuffle function creates a slice of shuffled values, using a version of the Fisher-Yates shuffle.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Shuffle1)
data := []int{1, 2, 3, 4}
result := From(data).Shuffle().Result()

fmt.Println(result)
/*
	the result can be this:
	  []int{ 1, 4, 2, 3 }

	this:
	  []int{ 4, 1, 2, 3 }

	or this:
	  []int{ 4, 1, 3, 2 }

	or this:
	  []int{ 3, 4, 1, 2 }

	or ... any other possibilities.
*/ities.
*/
Output:

Example (Shuffle2)
type Book struct {
	EbookName      string
	DailyDownloads int
}

data := []Book{
	{EbookName: "clean code", DailyDownloads: 10000},
	{EbookName: "rework", DailyDownloads: 12000},
	{EbookName: "detective comics", DailyDownloads: 11500},
}

result := From(data).Shuffle().Result()

fmt.Println(result)
/*
	  the result can be this:
		[]Book {
		  { EbookName: "detective comics", DailyDownloads: 11500 },
		  { EbookName: "clean code", DailyDownloads: 10000 },
		  { EbookName: "rework", DailyDownloads: 12000 },
		}

	  this:
		[]Book {
		  { EbookName: "clean code", DailyDownloads: 10000 },
		  { EbookName: "detective comics", DailyDownloads: 11500 },
		  { EbookName: "rework", DailyDownloads: 12000 },
		}

	  or this:
		[]Book {
		  { EbookName: "rework", DailyDownloads: 12000 },
		  { EbookName: "detective comics", DailyDownloads: 11500 },
		  { EbookName: "clean code", DailyDownloads: 10000 },
		}
*/: 10000 },
		}
*/
Output:

func (*Chainable) Size

func (g *Chainable) Size() IChainable

Size function gets the size of slice or struct object/map by returning its length for array-like values or the number of own enumerable string keyed properties for objects.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() int                  // ==> description: returns the length of data
.ResultAndError() (int, error) // ==> description: returns the length of data, and error object
.Error() error                 // ==> description: returns error object
.IsError() bool                // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (SizeMap)
data := map[string]interface{}{
	"name":   "noval",
	"age":    24,
	"isMale": true,
}

result := From(data).Size().Result()

fmt.Println(result)
// ===> 3
Output:

Example (SizeSlice)
From([]int{1, 2, 3, 4, 5}).Size().Result() // ===> 5
From("bruce").Size().Result()              // ===> 5
Output:

func (*Chainable) Tail

func (g *Chainable) Tail() IChainable

Tail function gets all but the first element of `data`.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() int                  // ==> description: returns the length of data
.ResultAndError() (int, error) // ==> description: returns the length of data, and error object
.Error() error                 // ==> description: returns error object
.IsError() bool                // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Tail1)
data := []string{"jason", "damian", "grayson", "tim"}
result := From(data).Tail().Result()

fmt.Println(result)
// ===> []string{ "damian", "grayson", "tim" }
Output:

Example (Tail2)
data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
result := From(data).Tail().Result()

fmt.Println(result)
// ===> []int{ 2, 3, 4, 5, 6, 7, 8, 9 }
Output:

func (*Chainable) Take

func (g *Chainable) Take(size int) IChainable

Take function creates a slice of `data` with `size` elements taken from the beginning.

Parameters

This function requires single mandatory parameter:

size int // ==> description: the length of each chunk

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Take1)
data := []string{"jason", "damian", "grayson", "tim"}
take := 2

result := From(data).Take(take).Result()

fmt.Println(result)
// ===> []string{ "jason", "damian" }
Output:

Example (Take2)
data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
take := 5

result := From(data).Take(take).Result()

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

func (*Chainable) TakeRight

func (g *Chainable) TakeRight(size int) IChainable

TakeRight function creates a slice of `data` with `size` elements taken from the end.

Parameters

This function requires single mandatory parameter:

size int // ==> description: the length of each chunk

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (TakeRight1)
data := []string{"jason", "damian", "grayson", "tim"}
take := 2

result := From(data).TakeRight(take).Result()

fmt.Println(result)
// ===> []string{ "grayson", "tim" }
Output:

Example (TakeRight2)
data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
take := 5

result := From(data).TakeRight(take).Result()

fmt.Println(result)
// ===> []int{ 5, 6, 7, 8, 9 }
Output:

func (*Chainable) UnionMany

func (g *Chainable) UnionMany(sliceToUnion ...interface{}) IChainable

Union function combines all slices presented on the parameters, then create slice of unique values from it. All slice must have same data type.

Parameters

This function requires optional variadic parameters:

sliceToUnion1 interface{} // ==> description: the index of item to exclude
sliceToUnion2 interface{} // ==> description: the index of item to exclude
sliceToUnion3 interface{} // ==> description: the index of item to exclude
...

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (UnionMany1)
result := From([]string{"damian", "grayson", "grayson", "cassandra"}).
	UnionMany(
		[]string{"tim", "grayson", "jason", "stephanie"},
		[]string{"duke"},
	).
	Result()

fmt.Println(result)
// ===> []string{ "damian", "grayson", "cassandra", "tim", "jason", "stephanie", "duke" }
Output:

Example (UnionMany2)
result := From([]int{1, 2, 3}).
	UnionMany(
		[]int{2, 3, 4, 5, 6},
		[]int{2, 5, 7, 8},
		[]int{9},
	).
	Result()

fmt.Println(result)
// ===> []int{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }
Output:

func (*Chainable) Uniq

func (g *Chainable) Uniq() IChainable

Uniq create slice of unique values from it.

Parameters

This function does not requires any parameter.

Return values

Chain with these methods to get result:

.Result() interface{}                  // ==> description: returns the result after operation
.ResultAndError() (interface{}, error) // ==> description: returns the result after operation, and error object
.Error() error                         // ==> description: returns error object
.IsError() bool                        // ==> description: return `true` on error, otherwise `false`

Examples

List of examples available:

Example (Uniq1)
data := []string{"damian", "grayson", "grayson", "cassandra"}
result := From(data).Uniq().Result()

fmt.Println(result)
// ===> []string{ "damian", "grayson", "cassandra" }
Output:

Example (Uniq2)
data := []float64{1.1, 3.00000, 3.1, 2.2000000, 3, 2.2, 3.0}
result := From(data).Uniq().Result()

fmt.Println(result)
// ===> []float64{ 1.1, 3, 3.1, 2.2 }
Output:

type IChainable

type IChainable interface {
	IChainableOperation

	ResultAndError() (interface{}, error)
	Result() interface{}
	Error() error
	IsError() bool
	LastSuccessOperation() Operation
	LastErrorOperation() Operation
	LastOperation() Operation
}

IChainable is the base interface for chainable functions It is contain the `IChainableOperation` interface (embedded), and result-related methods

func From

func From(data interface{}) IChainable

From is the initial function to use gubrak chainable operation. This function requires one argument, the data that are going to be used in operations

type IChainableBoolResult

type IChainableBoolResult interface {
	ResultAndError() (bool, error)
	Result() bool
	Error() error
	IsError() bool
	LastSuccessOperation() Operation
	LastErrorOperation() Operation
	LastOperation() Operation
}

type IChainableNoReturnValueResult

type IChainableNoReturnValueResult interface {
	Error() error
	IsError() bool
}

type IChainableNumberResult

type IChainableNumberResult interface {
	ResultAndError() (int, error)
	Result() int
	Error() error
	IsError() bool
	LastSuccessOperation() Operation
	LastErrorOperation() Operation
	LastOperation() Operation
}

type IChainableOperation

type IChainableOperation interface {
	Chunk(int) IChainable
	Compact() IChainable
	ConcatMany(...interface{}) IChainable
	Concat(interface{}) IChainable
	CountBy(interface{}) IChainableNumberResult
	Count() IChainableNumberResult
	DifferenceMany(...interface{}) IChainable
	Difference(interface{}) IChainable
	Drop(int) IChainable
	DropRight(int) IChainable
	Each(interface{}) IChainableNoReturnValueResult
	EachRight(interface{}) IChainableNoReturnValueResult
	Exclude(interface{}) IChainable
	ExcludeMany(...interface{}) IChainable
	ExcludeAt(int) IChainable
	ExcludeAtMany(...int) IChainable
	Fill(interface{}, ...int) IChainable
	Filter(interface{}) IChainable
	Find(interface{}, ...int) IChainable
	FindIndex(interface{}, ...int) IChainable
	FindLast(interface{}, ...int) IChainable
	FindLastIndex(interface{}, ...int) IChainable
	First() IChainable
	FromPairs() IChainable
	GroupBy(interface{}) IChainable
	Contains(interface{}, ...int) IChainableBoolResult
	IndexOf(interface{}, ...int) IChainableNumberResult
	Initial() IChainable
	Intersection(interface{}) IChainable
	IntersectionMany(data ...interface{}) IChainable
	Join(string) IChainableStringResult
	KeyBy(interface{}) IChainable
	Last() IChainable
	LastIndexOf(interface{}, ...int) IChainableNumberResult
	Map(interface{}) IChainable
	Nth(int) IChainable
	OrderBy(interface{}, ...bool) IChainable
	Partition(interface{}) IChainableTwoReturnValueResult
	Reduce(interface{}, interface{}) IChainable
	Reject(interface{}) IChainable
	Reverse() IChainable
	Sample() IChainable
	SampleSize(int) IChainable
	Shuffle() IChainable
	Size() IChainable
	Tail() IChainable
	Take(int) IChainable
	TakeRight(int) IChainable
	Uniq() IChainable
	UnionMany(...interface{}) IChainable
}

IChainableOperation is interface for chainable functions declaration

type IChainableStringResult

type IChainableStringResult interface {
	ResultAndError() (string, error)
	Result() string
	Error() error
	IsError() bool
}

type IChainableTwoReturnValueResult

type IChainableTwoReturnValueResult interface {
	ResultAndError() (interface{}, interface{}, error)
	ResultTruthy() interface{}
	ResultFalsey() interface{}
	Error() error
	IsError() bool
}

type Operation

type Operation string

Operation represent the type of chainable operation

Jump to

Keyboard shortcuts

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