funk

package module
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2022 License: MIT Imports: 6 Imported by: 1,406

README

go-funk
=======

.. image:: https://secure.travis-ci.org/thoas/go-funk.svg?branch=master
    :alt: Build Status
    :target: http://travis-ci.org/thoas/go-funk

.. image:: https://godoc.org/github.com/thoas/go-funk?status.svg
    :alt: GoDoc
    :target: https://pkg.go.dev/github.com/thoas/go-funk

.. image:: https://goreportcard.com/badge/github.com/thoas/go-funk
    :alt: Go report
    :target: https://goreportcard.com/report/github.com/thoas/go-funk

``go-funk`` is a modern Go library based on reflect_.

Generic helpers rely on reflect_, be careful this code runs exclusively on runtime so you must have a good test suite.

These helpers have started as an experiment to learn reflect_. It may look like lodash_ in some aspects but
it will have its own roadmap. lodash_ is an awesome library with a lot of work behind it, all features included in
``go-funk`` come from internal use cases.

You can also find typesafe implementation in the godoc_.

Why this name?
--------------

Long story, short answer because ``func`` is a reserved word in Go, I wanted something similar.

Initially this project was named ``fn`` I don't need to explain why that was a bad idea for french speakers :)

Let's ``funk``!

.. image:: https://media.giphy.com/media/3oEjHQKtDXpeGN9rW0/giphy.gif

<3

Installation
------------

.. code-block:: bash

    go get github.com/thoas/go-funk

Usage
-----

.. code-block:: go

    import "github.com/thoas/go-funk"

These examples will be based on the following data model:

.. code-block:: go

    type Foo struct {
        ID        int
        FirstName string `tag_name:"tag 1"`
        LastName  string `tag_name:"tag 2"`
        Age       int    `tag_name:"tag 3"`
    }

    func (f Foo) TableName() string {
        return "foo"
    }

With fixtures:

.. code-block:: go

    f := &Foo{
        ID:        1,
        FirstName: "Foo",
        LastName:  "Bar",
        Age:       30,
    }

You can import ``go-funk`` using a basic statement:

.. code-block:: go

    import "github.com/thoas/go-funk"

funk.Contains
.............

Returns true if an element is present in a iteratee (slice, map, string).

One frustrating thing in Go is to implement ``contains`` methods for each type, for example:

.. code-block:: go

    func ContainsInt(s []int, e int) bool {
        for _, a := range s {
            if a == e {
                return true
            }
        }
        return false
    }

this can be replaced by ``funk.Contains``:

.. code-block:: go

    // slice of string
    funk.Contains([]string{"foo", "bar"}, "bar") // true

    // slice of Foo ptr
    funk.Contains([]*Foo{f}, f) // true
    funk.Contains([]*Foo{f}, func (foo *Foo) bool {
        return foo.ID == f.ID
    }) // true
    funk.Contains([]*Foo{f}, nil) // false

    b := &Foo{
        ID:        2,
        FirstName: "Florent",
        LastName:  "Messa",
        Age:       28,
    }

    funk.Contains([]*Foo{f}, b) // false

    // string
    funk.Contains("florent", "rent") // true
    funk.Contains("florent", "foo") // false

    // even map
    funk.Contains(map[int]string{1: "Florent"}, 1) // true
    funk.Contains(map[int]string{1: "Florent"}, func(key int, name string) bool {
        return key == 1 // or `name == "Florent"` for the value type
    }) // true

see also, typesafe implementations: ContainsInt_, ContainsInt64_, ContainsFloat32_, ContainsFloat64_, ContainsString_

.. _ContainsFloat32: https://godoc.org/github.com/thoas/go-funk#ContainsFloat32
.. _ContainsFloat64: https://godoc.org/github.com/thoas/go-funk#ContainsFloat64
.. _ContainsInt: https://godoc.org/github.com/thoas/go-funk#ContainsInt
.. _ContainsInt64: https://godoc.org/github.com/thoas/go-funk#ContainsInt64
.. _ContainsString: https://godoc.org/github.com/thoas/go-funk#ContainsString

funk.Intersect
..............

Returns the intersection between two collections.

.. code-block:: go

    funk.Intersect([]int{1, 2, 3, 4}, []int{2, 4, 6})  // []int{2, 4}
    funk.Intersect([]string{"foo", "bar", "hello", "bar"}, []string{"foo", "bar"})  // []string{"foo", "bar"}

see also, typesafe implementations: IntersectString

.. IntersectString: https://godoc.org/github.com/thoas/go-funk#IntersectString


funk.Difference
..............

Returns the difference between two collections.

.. code-block:: go

    funk.Difference([]int{1, 2, 3, 4}, []int{2, 4, 6})  // []int{1, 3}, []int{6}
    funk.Difference([]string{"foo", "bar", "hello", "bar"}, []string{"foo", "bar"})  // []string{"hello"}, []string{}

see also, typesafe implementations: DifferenceString

.. DifferenceString: https://godoc.org/github.com/thoas/go-funk#DifferenceString


funk.IndexOf
............

Gets the index at which the first occurrence of a value is found in an array or return -1
if the value cannot be found.

.. code-block:: go

    // slice of string
    funk.IndexOf([]string{"foo", "bar"}, "bar") // 1
    funk.IndexOf([]string{"foo", "bar"}, func(value string) bool {
        return value == "bar"
    }) // 1
    funk.IndexOf([]string{"foo", "bar"}, "gilles") // -1

see also, typesafe implementations: IndexOfInt_, IndexOfInt64_, IndexOfFloat32_, IndexOfFloat64_, IndexOfString_

.. _IndexOfFloat32: https://godoc.org/github.com/thoas/go-funk#IndexOfFloat32
.. _IndexOfFloat64: https://godoc.org/github.com/thoas/go-funk#IndexOfFloat64
.. _IndexOfInt: https://godoc.org/github.com/thoas/go-funk#IndexOfInt
.. _IndexOfInt64: https://godoc.org/github.com/thoas/go-funk#IndexOfInt64
.. _IndexOfString: https://godoc.org/github.com/thoas/go-funk#IndexOfString

funk.LastIndexOf
................

Gets the index at which the last occurrence of a value is found in an array or return -1
if the value cannot be found.

.. code-block:: go

    // slice of string
    funk.LastIndexOf([]string{"foo", "bar", "bar"}, "bar") // 2
    funk.LastIndexOf([]string{"foo", "bar"}, func(value string) bool {
        return value == "bar"
    }) // 2
    funk.LastIndexOf([]string{"foo", "bar"}, "gilles") // -1

see also, typesafe implementations: LastIndexOfInt_, LastIndexOfInt64_, LastIndexOfFloat32_, LastIndexOfFloat64_, LastIndexOfString_

.. _LastIndexOfFloat32: https://godoc.org/github.com/thoas/go-funk#LastIndexOfFloat32
.. _LastIndexOfFloat64: https://godoc.org/github.com/thoas/go-funk#LastIndexOfFloat64
.. _LastIndexOfInt: https://godoc.org/github.com/thoas/go-funk#LastIndexOfInt
.. _LastIndexOfInt64: https://godoc.org/github.com/thoas/go-funk#LastIndexOfInt64
.. _LastIndexOfString: https://godoc.org/github.com/thoas/go-funk#LastIndexOfString

funk.ToMap
..........

Transforms a slice or an array of structs to a map based on a ``pivot`` field.

.. code-block:: go

    f := &Foo{
        ID:        1,
        FirstName: "Gilles",
        LastName:  "Fabio",
        Age:       70,
    }

    b := &Foo{
        ID:        2,
        FirstName: "Florent",
        LastName:  "Messa",
        Age:       80,
    }

    results := []*Foo{f, b}

    mapping := funk.ToMap(results, "ID") // map[int]*Foo{1: f, 2: b}

funk.ToSet
..........

Transforms an array or a slice to a set (a map with zero-size values).

.. code-block:: go

    f := Foo{
        ID:        1,
        FirstName: "Gilles",
        LastName:  "Fabio",
        Age:       70,
    }

    b := Foo{
        ID:        2,
        FirstName: "Florent",
        LastName:  "Messa",
        Age:       80,
    }

    mapping := funk.ToSet([]Foo{f, b}) // map[Foo]stuct{}{f: struct{}{}, b: struct{}{}}

    mapping := funk.ToSet([4]int{1, 1, 2, 2}) // map[int]struct{}{1: struct{}{}, 2: struct{}{}}



funk.Filter
...........

Filters a slice based on a predicate.

.. code-block:: go

    r := funk.Filter([]int{1, 2, 3, 4}, func(x int) bool {
        return x%2 == 0
    }) // []int{2, 4}

see also, typesafe implementations: FilterInt_, FilterInt64_, FilterFloat32_, FilterFloat64_, FilterString_

.. _FilterFloat32: https://godoc.org/github.com/thoas/go-funk#FilterFloat32
.. _FilterFloat64: https://godoc.org/github.com/thoas/go-funk#FilterFloat64
.. _FilterInt: https://godoc.org/github.com/thoas/go-funk#FilterInt
.. _FilterInt64: https://godoc.org/github.com/thoas/go-funk#FilterInt64
.. _FilterString: https://godoc.org/github.com/thoas/go-funk#FilterString

funk.Reduce
...........

Reduces an iteratee based on an accumulator function or operation rune for numbers.

.. code-block:: go

    // Using operation runes. '+' and '*' only supported.
    r := funk.Reduce([]int{1, 2, 3, 4}, '+', float64(0)) // 10
    r := funk.Reduce([]int{1, 2, 3, 4}, '*', 1) // 24

    // Using accumulator function
    r := funk.Reduce([]int{1, 2, 3, 4}, func(acc float64, num int) float64 {
        return acc + float64(num)
    }, float64(0)) // 10

    r := funk.Reduce([]int{1, 2, 3, 4}, func(acc string, num int) string {
        return acc + fmt.Sprint(num)
    }, "") // "1234"

funk.Find
.........

Finds an element in a slice based on a predicate.

.. code-block:: go

    r := funk.Find([]int{1, 2, 3, 4}, func(x int) bool {
        return x%2 == 0
    }) // 2

see also, typesafe implementations: FindInt_, FindInt64_, FindFloat32_, FindFloat64_, FindString_

.. _FindFloat32: https://godoc.org/github.com/thoas/go-funk#FindFloat32
.. _FindFloat64: https://godoc.org/github.com/thoas/go-funk#FindFloat64
.. _FindInt: https://godoc.org/github.com/thoas/go-funk#FindInt
.. _FindInt64: https://godoc.org/github.com/thoas/go-funk#FindInt64
.. _FindString: https://godoc.org/github.com/thoas/go-funk#FindString

funk.Map
........

Manipulates an iteratee (map, slice) and transforms it to another type:

* map -> slice
* map -> map
* slice -> map
* slice -> slice

.. code-block:: go

    r := funk.Map([]int{1, 2, 3, 4}, func(x int) int {
        return x * 2
    }) // []int{2, 4, 6, 8}

    r := funk.Map([]int{1, 2, 3, 4}, func(x int) string {
        return "Hello"
    }) // []string{"Hello", "Hello", "Hello", "Hello"}

    r = funk.Map([]int{1, 2, 3, 4}, func(x int) (int, int) {
        return x, x
    }) // map[int]int{1: 1, 2: 2, 3: 3, 4: 4}

    mapping := map[int]string{
        1: "Florent",
        2: "Gilles",
    }

    r = funk.Map(mapping, func(k int, v string) int {
        return k
    }) // []int{1, 2}

    r = funk.Map(mapping, func(k int, v string) (string, string) {
        return fmt.Sprintf("%d", k), v
    }) // map[string]string{"1": "Florent", "2": "Gilles"}

funk.FlatMap
............

Manipulates an iteratee (map, slice) and transforms it to to a flattened collection of another type:

* map -> slice
* slice -> slice

.. code-block:: go

    r := funk.FlatMap([][]int{{1, 2}, {3, 4}}, func(x []int) []int {
        return append(x, 0)
    }) // []int{1, 2, 0, 3, 4, 0}

    mapping := map[string][]int{
        "Florent": {1, 2},
        "Gilles": {3, 4},
    }

    r = funk.FlatMap(mapping, func(k string, v []int) []int {
        return v
    }) // []int{1, 2, 3, 4}

funk.Get
........

Retrieves the value at path of struct(s) or map(s).

.. code-block:: go

    var bar *Bar = &Bar{
        Name: "Test",
        Bars: []*Bar{
            &Bar{
                Name: "Level1-1",
                Bar: &Bar{
                    Name: "Level2-1",
                },
            },
            &Bar{
                Name: "Level1-2",
                Bar: &Bar{
                    Name: "Level2-2",
                },
            },
        },
    }

    var foo *Foo = &Foo{
        ID:        1,
        FirstName: "Dark",
        LastName:  "Vador",
        Age:       30,
        Bar:       bar,
        Bars: []*Bar{
            bar,
            bar,
        },
    }

    funk.Get([]*Foo{foo}, "Bar.Bars.Bar.Name") // []string{"Level2-1", "Level2-2"}
    funk.Get(foo, "Bar.Bars.Bar.Name") // []string{"Level2-1", "Level2-2"}
    funk.Get(foo, "Bar.Name") // Test

``funk.Get`` also support ``map`` values:

.. code-block:: go

    bar := map[string]interface{}{
        "Name": "Test",
    }

    foo1 := map[string]interface{}{
        "ID":        1,
        "FirstName": "Dark",
        "LastName":  "Vador",
        "Age":       30,
        "Bar":       bar,
    }

    foo2 := &map[string]interface{}{
        "ID":        1,
        "FirstName": "Dark",
        "LastName":  "Vador",
        "Age":       30,
        "Labels": map[string]interface{} {
            "example.com/hello": "world",
        },
    } // foo2.Bar is nil

    funk.Get(bar, "Name") // "Test"
    funk.Get([]map[string]interface{}{foo1, foo2}, "Bar.Name") // []string{"Test"}
    funk.Get(foo2, "Bar.Name") // nil
    funk.Get(foo2, `Labels."example.com/hello"`) // world


``funk.Get`` also handles ``nil`` values:

.. code-block:: go

    bar := &Bar{
        Name: "Test",
    }

    foo1 := &Foo{
        ID:        1,
        FirstName: "Dark",
        LastName:  "Vador",
        Age:       30,
        Bar:       bar,
    }

    foo2 := &Foo{
        ID:        1,
        FirstName: "Dark",
        LastName:  "Vador",
        Age:       30,
    } // foo2.Bar is nil

    funk.Get([]*Foo{foo1, foo2}, "Bar.Name") // []string{"Test"}
    funk.Get(foo2, "Bar.Name") // nil



funk.GetOrElse
..............

Retrieves the value of the pointer or default.

.. code-block:: go

    str := "hello world"
    GetOrElse(&str, "foobar")   // string{"hello world"}
    GetOrElse(str, "foobar")    // string{"hello world"}
    GetOrElse(nil, "foobar")    // string{"foobar"}

funk.Set
........
Set value at a path of a struct

.. code-block:: go

    var bar Bar = Bar{
        Name: "level-0",
        Bar: &Bar{
            Name: "level-1",
            Bars: []*Bar{
                {Name: "level2-1"},
                {Name: "level2-2"},
            },
        },
    }

    _ = Set(&bar, "level-0-new", "Name")
    fmt.Println(bar.Name) // "level-0-new"

    MustSet(&bar, "level-1-new", "Bar.Name")
    fmt.Println(bar.Bar.Name) // "level-1-new"

    Set(&bar, "level-2-new", "Bar.Bars.Name")
    fmt.Println(bar.Bar.Bars[0].Name) // "level-2-new"
    fmt.Println(bar.Bar.Bars[1].Name) // "level-2-new"

funk.MustSet
............
Short hand for funk.Set if struct does not contain interface{} field type to discard errors.

funk.Prune
..........
Copy a struct with only selected fields. Slice is handled by pruning all elements.

.. code-block:: go

    bar := &Bar{
        Name: "Test",
    }

    foo1 := &Foo{
        ID:        1,
        FirstName: "Dark",
        LastName:  "Vador",
        Bar:       bar,
    }

    pruned, _ := Prune(foo1, []string{"FirstName", "Bar.Name"})
    // *Foo{
    //    ID:        0,
    //    FirstName: "Dark",
    //    LastName:  "",
    //    Bar:       &Bar{Name: "Test},
    // }

funk.PruneByTag
..........
Same functionality as funk.Prune, but uses struct tags instead of struct field names.

funk.Keys
.........

Creates an array of the own enumerable map keys or struct field names.

.. code-block:: go

    funk.Keys(map[string]int{"one": 1, "two": 2}) // []string{"one", "two"} (iteration order is not guaranteed)

    foo := &Foo{
        ID:        1,
        FirstName: "Dark",
        LastName:  "Vador",
        Age:       30,
    }

    funk.Keys(foo) // []string{"ID", "FirstName", "LastName", "Age"} (iteration order is not guaranteed)

funk.Values
...........

Creates an array of the own enumerable map values or struct field values.

.. code-block:: go

    funk.Values(map[string]int{"one": 1, "two": 2}) // []int{1, 2} (iteration order is not guaranteed)

    foo := &Foo{
        ID:        1,
        FirstName: "Dark",
        LastName:  "Vador",
        Age:       30,
    }

    funk.Values(foo) // []interface{}{1, "Dark", "Vador", 30} (iteration order is not guaranteed)

funk.ForEach
............

Range over an iteratee (map, slice).

Or update element in slice(Not map, reflect#Value#MapIndex#CanSet is false).

.. code-block:: go

    funk.ForEach([]int{1, 2, 3, 4}, func(x int) {
        fmt.Println(x)
    })

    foo := []int{1,2,3}
    funk.ForEach(foo, func(x *int){ *x = *x * 2})
    fmt.Println(foo) // []int{2, 4, 6}

funk.ForEachRight
............

Range over an iteratee (map, slice) from the right.

.. code-block:: go

    results := []int{}

    funk.ForEachRight([]int{1, 2, 3, 4}, func(x int) {
        results = append(results, x)
    })

    fmt.Println(results) // []int{4, 3, 2, 1}

funk.Chunk
..........

Creates an array of elements split into groups with the length of the size.
If array can't be split evenly, the final chunk will be the remaining element.

.. code-block:: go

    funk.Chunk([]int{1, 2, 3, 4, 5}, 2) // [][]int{[]int{1, 2}, []int{3, 4}, []int{5}}

funk.FlattenDeep
................

Recursively flattens an array.

.. code-block:: go

    funk.FlattenDeep([][]int{[]int{1, 2}, []int{3, 4}}) // []int{1, 2, 3, 4}

funk.Uniq
.........

Creates an array with unique values.

.. code-block:: go

    funk.Uniq([]int{0, 1, 1, 2, 3, 0, 0, 12}) // []int{0, 1, 2, 3, 12}

see also, typesafe implementations: UniqInt_, UniqInt64_, UniqFloat32_, UniqFloat64_, UniqString_

.. _UniqFloat32: https://godoc.org/github.com/thoas/go-funk#UniqFloat32
.. _UniqFloat64: https://godoc.org/github.com/thoas/go-funk#UniqFloat64
.. _UniqInt: https://godoc.org/github.com/thoas/go-funk#UniqInt
.. _UniqInt64: https://godoc.org/github.com/thoas/go-funk#UniqInt64
.. _UniqString: https://godoc.org/github.com/thoas/go-funk#UniqString

funk.UniqBy
.........

Creates an array with unique values returned by a callback.

.. code-block:: go

    funk.UniqBy([]int{0, 1, 1, 2, 3, 0, 0, 12}, func(nbr int) int {
		return nbr % 3
	}) // []int{0, 1, 2}

    foo1 := Foo{
        ID: 42,
        FirstName: "Bob",
    }
    foo2 := Foo{
        ID: 42,
        FirstName: "Bob",
    }
    funk.UniqBy([]Foo{foo1, foo2}, func(f Foo) int {
		return f.ID
	}) // []Foo{ Foo{ID: 42, Firstname: "Bob"} }

funk.Drop
.........

Creates an array/slice with `n` elements dropped from the beginning.

.. code-block:: go

    funk.Drop([]int{0, 0, 0, 0}, 3) // []int{0}

see also, typesafe implementations: DropInt_, DropInt32_, DropInt64_, DropFloat32_, DropFloat64_, DropString_

.. _DropInt: https://godoc.org/github.com/thoas/go-funk#DropInt
.. _DropInt32: https://godoc.org/github.com/thoas/go-funk#DropInt64
.. _DropInt64: https://godoc.org/github.com/thoas/go-funk#DropInt64
.. _DropFloat32: https://godoc.org/github.com/thoas/go-funk#DropFloat32
.. _DropFloat64: https://godoc.org/github.com/thoas/go-funk#DropFloat64
.. _DropString: https://godoc.org/github.com/thoas/go-funk#DropString

funk.Initial
............

Gets all but the last element of array.

.. code-block:: go

    funk.Initial([]int{0, 1, 2, 3, 4}) // []int{0, 1, 2, 3}

funk.Tail
.........

Gets all but the first element of array.

.. code-block:: go

    funk.Tail([]int{0, 1, 2, 3, 4}) // []int{1, 2, 3, 4}

funk.Shuffle
............

Creates an array of shuffled values.

.. code-block:: go

    funk.Shuffle([]int{0, 1, 2, 3, 4}) // []int{2, 1, 3, 4, 0}


see also, typesafe implementations: ShuffleInt_, ShuffleInt64_, ShuffleFloat32_, ShuffleFloat64_, ShuffleString_

.. _ShuffleFloat32: https://godoc.org/github.com/thoas/go-funk#ShuffleFloat32
.. _ShuffleFloat64: https://godoc.org/github.com/thoas/go-funk#ShuffleFloat64
.. _ShuffleInt: https://godoc.org/github.com/thoas/go-funk#ShuffleInt
.. _ShuffleInt64: https://godoc.org/github.com/thoas/go-funk#ShuffleInt64
.. _ShuffleString: https://godoc.org/github.com/thoas/go-funk#ShuffleString

funk.Subtract
.............

Returns the subtraction between two collections. It preserve order.

.. code-block:: go

    funk.Subtract([]int{0, 1, 2, 3, 4}, []int{0, 4}) // []int{1, 2, 3}
    funk.Subtract([]int{0, 3, 2, 3, 4}, []int{0, 4}) // []int{3, 2, 3}


see also, typesafe implementations: SubtractString_

.. SubtractString: https://godoc.org/github.com/thoas/go-funk#SubtractString

funk.Sum
........

Computes the sum of the values in an array.

.. code-block:: go

    funk.Sum([]int{0, 1, 2, 3, 4}) // 10.0
    funk.Sum([]interface{}{0.5, 1, 2, 3, 4}) // 10.5

see also, typesafe implementations: SumInt_, SumInt64_, SumFloat32_, SumFloat64_

.. _SumFloat32: https://godoc.org/github.com/thoas/go-funk#SumFloat32
.. _SumFloat64: https://godoc.org/github.com/thoas/go-funk#SumFloat64
.. _SumInt: https://godoc.org/github.com/thoas/go-funk#SumInt
.. _SumInt64: https://godoc.org/github.com/thoas/go-funk#SumInt64

funk.Reverse
............

Transforms an array such that the first element will become the last, the second element
will become the second to last, etc.

.. code-block:: go

    funk.Reverse([]int{0, 1, 2, 3, 4}) // []int{4, 3, 2, 1, 0}

see also, typesafe implementations: ReverseInt_, ReverseInt64_, ReverseFloat32_, ReverseFloat64_, ReverseString_, ReverseStrings_

.. _ReverseFloat32: https://godoc.org/github.com/thoas/go-funk#ReverseFloat32
.. _ReverseFloat64: https://godoc.org/github.com/thoas/go-funk#ReverseFloat64
.. _ReverseInt: https://godoc.org/github.com/thoas/go-funk#ReverseInt
.. _ReverseInt64: https://godoc.org/github.com/thoas/go-funk#ReverseInt64
.. _ReverseString: https://godoc.org/github.com/thoas/go-funk#ReverseString
.. _ReverseStrings: https://godoc.org/github.com/thoas/go-funk#ReverseStrings

funk.SliceOf
............

Returns a slice based on an element.

.. code-block:: go

    funk.SliceOf(f) // will return a []*Foo{f}

funk.RandomInt
..............

Generates a random int, based on a min and max values.

.. code-block:: go

    funk.RandomInt(0, 100) // will be between 0 and 100

funk.RandomString
.................

Generates a random string with a fixed length.

.. code-block:: go

    funk.RandomString(4) // will be a string of 4 random characters

funk.Shard
..........

Generates a sharded string with a fixed length and depth.

.. code-block:: go

    funk.Shard("e89d66bdfdd4dd26b682cc77e23a86eb", 1, 2, false) // []string{"e", "8", "e89d66bdfdd4dd26b682cc77e23a86eb"}

    funk.Shard("e89d66bdfdd4dd26b682cc77e23a86eb", 2, 2, false) // []string{"e8", "9d", "e89d66bdfdd4dd26b682cc77e23a86eb"}

    funk.Shard("e89d66bdfdd4dd26b682cc77e23a86eb", 2, 3, true) // []string{"e8", "9d", "66", "bdfdd4dd26b682cc77e23a86eb"}

funk.Subset
.............

Returns true if a collection is a subset of another

.. code-block:: go

    funk.Subset([]int{1, 2, 4}, []int{1, 2, 3, 4, 5}) // true
    funk.Subset([]string{"foo", "bar"},[]string{"foo", "bar", "hello", "bar", "hi"}) //true


Performance
-----------

``go-funk`` currently has an open issue about performance_, don't hesitate to participate in the discussion
to enhance the generic helpers implementations.

Let's stop beating around the bush, a typesafe implementation in pure Go of ``funk.Contains``, let's say for example:

.. code-block:: go

    func ContainsInt(s []int, e int) bool {
        for _, a := range s {
            if a == e {
                return true
            }
        }
        return false
    }

will always outperform an implementation based on reflect_ in terms of speed and allocs because of
how it's implemented in the language.

If you want a similarity, gorm_ will always be slower than sqlx_ (which is very low level btw) and will use more allocs.

You must not think generic helpers of ``go-funk`` as a replacement when you are dealing with performance in your codebase,
you should use typesafe implementations instead.

Contributing
------------

* Ping me on twitter `@thoas <https://twitter.com/thoas>`_ (DMs, mentions, whatever :))
* Fork the `project <https://github.com/thoas/go-funk>`_
* Fix `open issues <https://github.com/thoas/go-funk/issues>`_ or request new features

Don't hesitate ;)

Authors
-------

* Florent Messa
* Gilles Fabio
* Alexey Pokhozhaev
* Alexandre Nicolaie

.. _reflect: https://golang.org/pkg/reflect/
.. _lodash: https://lodash.com/
.. _performance: https://github.com/thoas/go-funk/issues/19
.. _gorm: https://github.com/jinzhu/gorm
.. _sqlx: https://github.com/jmoiron/sqlx
.. _godoc: https://godoc.org/github.com/thoas/go-funk

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All(objs ...interface{}) bool

All returns true if all elements of the iterable are not empty (or if the iterable is empty)

func AllPredicates added in v0.8.0

func AllPredicates(value interface{}, predicates interface{}) bool

AllPredicates gets a value and a series of predicates, and return true if all of the predicates are true.

func Any

func Any(objs ...interface{}) bool

Any returns true if any element of the iterable is not empty. If the iterable is empty, return False.

func AnyPredicates added in v0.8.0

func AnyPredicates(value interface{}, predicates interface{}) bool

AnyPredicates gets a value and a series of predicates, and return true if at least one of the predicates is true.

func Chunk

func Chunk(arr interface{}, size int) interface{}

Chunk creates an array of elements split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func ChunkFloat64s added in v0.9.1

func ChunkFloat64s(arr []float64, size int) [][]float64

ChunkFloat64s creates an array of float64s split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func ChunkInt32s added in v0.9.1

func ChunkInt32s(arr []int32, size int) [][]int32

ChunkInt32s creates an array of int32s split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func ChunkInt64s added in v0.9.1

func ChunkInt64s(arr []int64, size int) [][]int64

ChunkInt64s creates an array of int64s split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func ChunkInts added in v0.9.1

func ChunkInts(arr []int, size int) [][]int

ChunkInts creates an array of ints split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func ChunkStrings added in v0.9.1

func ChunkStrings(arr []string, size int) [][]string

ChunkStrings creates an array of strings split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func ChunkUInt32s added in v0.9.3

func ChunkUInt32s(arr []uint32, size int) [][]uint32

ChunkUInt32s creates an array of uint32s split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func ChunkUInt64s added in v0.9.3

func ChunkUInt64s(arr []uint64, size int) [][]uint64

ChunkUInt64s creates an array of uint64s split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func ChunkUInts added in v0.9.3

func ChunkUInts(arr []uint, size int) [][]uint

ChunkUInts creates an array of uints split into groups with the length of size. If array can't be split evenly, the final chunk will be the remaining element.

func Compact

func Compact(value interface{}) interface{}

Compact creates a slice with all empty/zero values removed.

func Contains

func Contains(in interface{}, elem interface{}) bool

Contains returns true if an element is present in a iteratee.

func ContainsBool added in v0.9.0

func ContainsBool(s []bool, v bool) bool

ContainsBool returns true if a boolean is present in a iteratee.

func ContainsFloat32

func ContainsFloat32(s []float32, v float32) bool

ContainsFloat32 returns true if a float32 is present in a iteratee.

func ContainsFloat64

func ContainsFloat64(s []float64, v float64) bool

ContainsFloat64 returns true if a float64 is present in a iteratee.

func ContainsInt

func ContainsInt(s []int, v int) bool

ContainsInt returns true if an int is present in a iteratee.

func ContainsInt32

func ContainsInt32(s []int32, v int32) bool

ContainsInt32 returns true if an int32 is present in a iteratee.

func ContainsInt64

func ContainsInt64(s []int64, v int64) bool

ContainsInt64 returns true if an int64 is present in a iteratee.

func ContainsString

func ContainsString(s []string, v string) bool

ContainsString returns true if a string is present in a iteratee.

func ContainsUInt added in v0.8.0

func ContainsUInt(s []uint, v uint) bool

ContainsUInt returns true if an uint is present in a iteratee.

func ContainsUInt32 added in v0.8.0

func ContainsUInt32(s []uint32, v uint32) bool

ContainsUInt32 returns true if an uint32 is present in a iteratee.

func ContainsUInt64 added in v0.8.0

func ContainsUInt64(s []uint64, v uint64) bool

ContainsUInt64 returns true if an uint64 is present in a iteratee.

func ConvertSlice

func ConvertSlice(in interface{}, out interface{})

ConvertSlice converts a slice type to another, a perfect example would be to convert a slice of struct to a slice of interface.

func Difference added in v0.6.0

func Difference(x interface{}, y interface{}) (interface{}, interface{})

Difference returns the difference between two collections.

func DifferenceInt added in v0.8.0

func DifferenceInt(x []int, y []int) ([]int, []int)

DifferenceInt returns the difference between two collections of ints.

func DifferenceInt32 added in v0.8.0

func DifferenceInt32(x []int32, y []int32) ([]int32, []int32)

DifferenceInt32 returns the difference between two collections of ints32.

func DifferenceInt64 added in v0.8.0

func DifferenceInt64(x []int64, y []int64) ([]int64, []int64)

DifferenceInt64 returns the difference between two collections of int64s.

func DifferenceString added in v0.6.0

func DifferenceString(x []string, y []string) ([]string, []string)

DifferenceString returns the difference between two collections of strings.

func DifferenceUInt added in v0.8.0

func DifferenceUInt(x []uint, y []uint) ([]uint, []uint)

DifferenceUInt returns the difference between two collections of uints.

func DifferenceUInt32 added in v0.8.0

func DifferenceUInt32(x []uint32, y []uint32) ([]uint32, []uint32)

DifferenceUInt32 returns the difference between two collections of uints32.

func DifferenceUInt64 added in v0.8.0

func DifferenceUInt64(x []uint64, y []uint64) ([]uint64, []uint64)

DifferenceUInt64 returns the difference between two collections of uints64.

func Drop

func Drop(in interface{}, n int) interface{}

Drop creates an array/slice with `n` elements dropped from the beginning.

func DropBool added in v0.9.0

func DropBool(s []bool, n int) []bool

DropBool creates a slice with `n` bools dropped from the beginning.

func DropFloat32

func DropFloat32(s []float32, n int) []float32

DropFloat32 creates a slice with `n` float32s dropped from the beginning.

func DropFloat64

func DropFloat64(s []float64, n int) []float64

DropFloat64 creates a slice with `n` float64s dropped from the beginning.

func DropInt

func DropInt(s []int, n int) []int

DropInt creates a slice with `n` ints dropped from the beginning.

func DropInt32

func DropInt32(s []int32, n int) []int32

DropInt32 creates a slice with `n` int32s dropped from the beginning.

func DropInt64

func DropInt64(s []int64, n int) []int64

DropInt64 creates a slice with `n` int64s dropped from the beginning.

func DropString

func DropString(s []string, n int) []string

DropString creates a slice with `n` strings dropped from the beginning.

func DropUInt added in v0.8.0

func DropUInt(s []uint, n uint) []uint

DropUInt creates a slice with `n` ints dropped from the beginning.

func DropUInt32 added in v0.8.0

func DropUInt32(s []uint32, n int) []uint32

DropUInt32 creates a slice with `n` int32s dropped from the beginning.

func DropUInt64 added in v0.8.0

func DropUInt64(s []uint64, n int) []uint64

DropUInt64 creates a slice with `n` int64s dropped from the beginning.

func Equal

func Equal(expected interface{}, actual interface{}) bool

Equal returns if the two objects are equal

func Every

func Every(in interface{}, elements ...interface{}) bool

Every returns true if every element is present in a iteratee.

func Fill

func Fill(in interface{}, fillValue interface{}) (interface{}, error)

Fill fills elements of array with value

func Filter

func Filter(arr interface{}, predicate interface{}) interface{}

Filter iterates over elements of collection, returning an array of all elements predicate returns truthy for.

func FilterBool added in v0.9.0

func FilterBool(s []bool, cb func(s bool) bool) []bool

FilterBool iterates over a collection of bool, returning an array of all bool elements predicate returns truthy for.

func FilterFloat32

func FilterFloat32(s []float32, cb func(s float32) bool) []float32

FilterFloat32 iterates over a collection of float32, returning an array of all float32 elements predicate returns truthy for.

func FilterFloat64

func FilterFloat64(s []float64, cb func(s float64) bool) []float64

FilterFloat64 iterates over a collection of float64, returning an array of all float64 elements predicate returns truthy for.

func FilterInt

func FilterInt(s []int, cb func(s int) bool) []int

FilterInt iterates over a collection of int, returning an array of all int elements predicate returns truthy for.

func FilterInt32

func FilterInt32(s []int32, cb func(s int32) bool) []int32

FilterInt32 iterates over a collection of int32, returning an array of all int32 elements predicate returns truthy for.

func FilterInt64

func FilterInt64(s []int64, cb func(s int64) bool) []int64

FilterInt64 iterates over a collection of int64, returning an array of all int64 elements predicate returns truthy for.

func FilterString

func FilterString(s []string, cb func(s string) bool) []string

FilterString iterates over a collection of string, returning an array of all string elements predicate returns truthy for.

func FilterUInt added in v0.8.0

func FilterUInt(s []uint, cb func(s uint) bool) []uint

FilterUInt iterates over a collection of uint, returning an array of all uint elements predicate returns truthy for.

func FilterUInt32 added in v0.8.0

func FilterUInt32(s []uint32, cb func(s uint32) bool) []uint32

FilterUInt32 iterates over a collection of uint32, returning an array of all uint32 elements predicate returns truthy for.

func FilterUInt64 added in v0.8.0

func FilterUInt64(s []uint64, cb func(s uint64) bool) []uint64

FilterUInt64 iterates over a collection of uint64, returning an array of all uint64 elements predicate returns truthy for.

func Find

func Find(arr interface{}, predicate interface{}) interface{}

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

func FindFloat32

func FindFloat32(s []float32, cb func(s float32) bool) (float32, bool)

FindFloat32 iterates over a collection of float32, returning the first float32 element predicate returns truthy for.

func FindFloat64

func FindFloat64(s []float64, cb func(s float64) bool) (float64, bool)

FindFloat64 iterates over a collection of float64, returning an array of all float64 elements predicate returns truthy for.

func FindInt

func FindInt(s []int, cb func(s int) bool) (int, bool)

FindInt iterates over a collection of int, returning the first int element predicate returns truthy for.

func FindInt32

func FindInt32(s []int32, cb func(s int32) bool) (int32, bool)

FindInt32 iterates over a collection of int32, returning the first int32 element predicate returns truthy for.

func FindInt64

func FindInt64(s []int64, cb func(s int64) bool) (int64, bool)

FindInt64 iterates over a collection of int64, returning the first int64 element predicate returns truthy for.

func FindKey added in v0.5.0

func FindKey(arr interface{}, predicate interface{}) (matchKey, matchEle interface{})

Find iterates over elements of collection, returning the first element of an array and random of a map which predicate returns truthy for.

func FindString

func FindString(s []string, cb func(s string) bool) (string, bool)

FindString iterates over a collection of string, returning the first string element predicate returns truthy for.

func FlatMap added in v0.8.0

func FlatMap(arr interface{}, mapFunc interface{}) interface{}

FlatMap manipulates an iteratee and transforms it to a flattened collection of another type.

func Flatten added in v0.8.0

func Flatten(out interface{}) interface{}

Flatten flattens a two-dimensional array.

func FlattenDeep

func FlattenDeep(out interface{}) interface{}

FlattenDeep recursively flattens array.

func ForEach

func ForEach(arr interface{}, predicate interface{})

ForEach iterates over elements of collection and invokes iteratee for each element.

func ForEachRight

func ForEachRight(arr interface{}, predicate interface{})

ForEachRight iterates over elements of collection from the right and invokes iteratee for each element.

func Get

func Get(out interface{}, path string, opts ...option) interface{}

Get retrieves the value from given path, retriever can be modified with available RetrieverOptions

func GetOrElse added in v0.6.0

func GetOrElse(v interface{}, def interface{}) interface{}

GetOrElse retrieves the value of the pointer or default.

func Head(arr interface{}) interface{}

Head gets the first element of array.

func InBools added in v0.9.0

func InBools(s []bool, v bool) bool

InBools is an alias of ContainsBool, returns true if a bool is present in a iteratee.

func InFloat32s

func InFloat32s(s []float32, v float32) bool

InFloat32s is an alias of ContainsFloat32, returns true if a float32 is present in a iteratee.

func InFloat64s

func InFloat64s(s []float64, v float64) bool

InFloat64s is an alias of ContainsFloat64, returns true if a float64 is present in a iteratee.

func InInt32s

func InInt32s(s []int32, v int32) bool

InInt32s is an alias of ContainsInt32, returns true if an int32 is present in a iteratee.

func InInt64s

func InInt64s(s []int64, v int64) bool

InInt64s is an alias of ContainsInt64, returns true if an int64 is present in a iteratee.

func InInts

func InInts(s []int, v int) bool

InInts is an alias of ContainsInt, returns true if an int is present in a iteratee.

func InStrings

func InStrings(s []string, v string) bool

InStrings is an alias of ContainsString, returns true if a string is present in a iteratee.

func InUInt32s added in v0.8.0

func InUInt32s(s []uint32, v uint32) bool

InUInt32s is an alias of ContainsUInt32, returns true if an uint32 is present in a iteratee.

func InUInt64s added in v0.8.0

func InUInt64s(s []uint64, v uint64) bool

InUInt64s is an alias of ContainsUInt64, returns true if an uint64 is present in a iteratee.

func InUInts added in v0.8.0

func InUInts(s []uint, v uint) bool

InUInts is an alias of ContainsUInt, returns true if an uint is present in a iteratee.

func IndexOf

func IndexOf(in interface{}, elem interface{}) int

IndexOf gets the index at which the first occurrence of value is found in array or return -1 if the value cannot be found

func IndexOfBool added in v0.9.0

func IndexOfBool(a []bool, x bool) int

IndexOfBool gets the index at which the first occurrence of a bool value is found in array or return -1 if the value cannot be found

func IndexOfFloat64

func IndexOfFloat64(a []float64, x float64) int

IndexOfFloat64 gets the index at which the first occurrence of an float64 value is found in array or return -1 if the value cannot be found

func IndexOfInt

func IndexOfInt(a []int, x int) int

IndexOfInt gets the index at which the first occurrence of an int value is found in array or return -1 if the value cannot be found

func IndexOfInt32

func IndexOfInt32(a []int32, x int32) int

IndexOfInt32 gets the index at which the first occurrence of an int32 value is found in array or return -1 if the value cannot be found

func IndexOfInt64

func IndexOfInt64(a []int64, x int64) int

IndexOfInt64 gets the index at which the first occurrence of an int64 value is found in array or return -1 if the value cannot be found

func IndexOfString

func IndexOfString(a []string, x string) int

IndexOfString gets the index at which the first occurrence of a string value is found in array or return -1 if the value cannot be found

func IndexOfUInt added in v0.8.0

func IndexOfUInt(a []uint, x uint) int

IndexOfUInt gets the index at which the first occurrence of an uint value is found in array or return -1 if the value cannot be found

func IndexOfUInt32 added in v0.8.0

func IndexOfUInt32(a []uint32, x uint32) int

IndexOfUInt32 gets the index at which the first occurrence of an uint32 value is found in array or return -1 if the value cannot be found

func IndexOfUInt64 added in v0.8.0

func IndexOfUInt64(a []uint64, x uint64) int

IndexOfUInt64 gets the index at which the first occurrence of an uint64 value is found in array or return -1 if the value cannot be found

func Initial

func Initial(arr interface{}) interface{}

Initial gets all but the last element of array.

func InnerJoin added in v0.7.0

func InnerJoin(lx, rx reflect.Value) reflect.Value

InnerJoin finds and returns matching data from two collections.

func InnerJoinFloat32 added in v0.7.0

func InnerJoinFloat32(lx, rx []float32) []float32

InnerJoinFloat32 finds and returns matching data from two float32 collections.

func InnerJoinFloat64 added in v0.7.0

func InnerJoinFloat64(lx, rx []float64) []float64

InnerJoinFloat64 finds and returns matching data from two float64 collections.

func InnerJoinInt added in v0.7.0

func InnerJoinInt(lx, rx []int) []int

InnerJoinInt finds and returns matching data from two int collections.

func InnerJoinInt32 added in v0.7.0

func InnerJoinInt32(lx, rx []int32) []int32

InnerJoinInt32 finds and returns matching data from two int32 collections.

func InnerJoinInt64 added in v0.7.0

func InnerJoinInt64(lx, rx []int64) []int64

InnerJoinInt64 finds and returns matching data from two int64 collections.

func InnerJoinString added in v0.7.0

func InnerJoinString(lx, rx []string) []string

InnerJoinString finds and returns matching data from two string collections.

func Intersect deprecated

func Intersect(x interface{}, y interface{}) interface{}

Intersect returns the intersection between two collections.

Deprecated: use Join(x, y, InnerJoin) instead of Intersect, InnerJoin implements deduplication mechanism, so verify your code behaviour before using it

func IntersectString

func IntersectString(x []string, y []string) []string

IntersectString returns the intersection between two collections of string.

func IsCollection

func IsCollection(in interface{}) bool

IsCollection returns if the argument is a collection.

func IsEmpty

func IsEmpty(obj interface{}) bool

IsEmpty returns if the object is considered as empty or not.

func IsEqual

func IsEqual(expected interface{}, actual interface{}) bool

IsEqual returns if the two objects are equal

func IsFunction

func IsFunction(in interface{}, num ...int) bool

IsFunction returns if the argument is a function.

func IsIteratee

func IsIteratee(in interface{}) bool

IsIteratee returns if the argument is an iteratee.

func IsPredicate added in v0.8.0

func IsPredicate(in interface{}, inTypes ...reflect.Type) bool

IsPredicate returns if the argument is a predicate function.

func IsType

func IsType(expected interface{}, actual interface{}) bool

IsType returns if the two objects are in the same type

func IsZero

func IsZero(obj interface{}) bool

IsZero returns if the object is considered as zero value

func Join added in v0.7.0

func Join(larr, rarr interface{}, fnc JoinFnc) interface{}

Join combines two collections using the given join method.

func JoinFloat32 added in v0.7.0

func JoinFloat32(larr, rarr []float32, fnc JoinFloat32Fnc) []float32

JoinFloat32 combines two float32 collections using the given join method.

func JoinFloat64 added in v0.7.0

func JoinFloat64(larr, rarr []float64, fnc JoinFloat64Fnc) []float64

JoinFloat64 combines two float64 collections using the given join method.

func JoinInt added in v0.7.0

func JoinInt(larr, rarr []int, fnc JoinIntFnc) []int

JoinInt combines two int collections using the given join method.

func JoinInt32 added in v0.7.0

func JoinInt32(larr, rarr []int32, fnc JoinInt32Fnc) []int32

JoinInt32 combines two int32 collections using the given join method.

func JoinInt64 added in v0.7.0

func JoinInt64(larr, rarr []int64, fnc JoinInt64Fnc) []int64

JoinInt64 combines two int64 collections using the given join method.

func JoinString added in v0.7.0

func JoinString(larr, rarr []string, fnc JoinStringFnc) []string

JoinString combines two string collections using the given join method.

func Keys

func Keys(out interface{}) interface{}

Keys creates an array of the own enumerable map keys or struct field names.

func Last

func Last(arr interface{}) interface{}

Last gets the last element of array.

func LastIndexOf

func LastIndexOf(in interface{}, elem interface{}) int

LastIndexOf gets the index at which the last occurrence of value is found in array or return -1 if the value cannot be found

func LastIndexOfBool added in v0.9.0

func LastIndexOfBool(a []bool, x bool) int

LastIndexOfBool gets the index at which the first occurrence of a bool value is found in array or return -1 if the value cannot be found

func LastIndexOfFloat32

func LastIndexOfFloat32(a []float32, x float32) int

LastIndexOfFloat32 gets the index at which the first occurrence of an float32 value is found in array or return -1 if the value cannot be found

func LastIndexOfFloat64

func LastIndexOfFloat64(a []float64, x float64) int

LastIndexOfFloat64 gets the index at which the first occurrence of an float64 value is found in array or return -1 if the value cannot be found

func LastIndexOfInt

func LastIndexOfInt(a []int, x int) int

LastIndexOfInt gets the index at which the first occurrence of an int value is found in array or return -1 if the value cannot be found

func LastIndexOfInt32

func LastIndexOfInt32(a []int32, x int32) int

LastIndexOfInt32 gets the index at which the first occurrence of an int32 value is found in array or return -1 if the value cannot be found

func LastIndexOfInt64

func LastIndexOfInt64(a []int64, x int64) int

LastIndexOfInt64 gets the index at which the first occurrence of an int64 value is found in array or return -1 if the value cannot be found

func LastIndexOfString

func LastIndexOfString(a []string, x string) int

LastIndexOfString gets the index at which the first occurrence of a string value is found in array or return -1 if the value cannot be found

func LastIndexOfUInt added in v0.8.0

func LastIndexOfUInt(a []uint, x uint) int

LastIndexOfUInt gets the index at which the first occurrence of an uint value is found in array or return -1 if the value cannot be found

func LastIndexOfUInt32 added in v0.8.0

func LastIndexOfUInt32(a []uint32, x uint32) int

LastIndexOfUInt32 gets the index at which the first occurrence of an uint32 value is found in array or return -1 if the value cannot be found

func LastIndexOfUInt64 added in v0.8.0

func LastIndexOfUInt64(a []uint64, x uint64) int

LastIndexOfUInt64 gets the index at which the first occurrence of an uint64 value is found in array or return -1 if the value cannot be found

func LeftJoin added in v0.7.0

func LeftJoin(lx, rx reflect.Value) reflect.Value

LeftJoin finds and returns dissimilar data from the first collection (left).

func LeftJoinFloat32 added in v0.7.0

func LeftJoinFloat32(lx, rx []float32) []float32

LeftJoinFloat32 finds and returns dissimilar data from the first float32 collection (left).

func LeftJoinFloat64 added in v0.7.0

func LeftJoinFloat64(lx, rx []float64) []float64

LeftJoinFloat64 finds and returns dissimilar data from the first float64 collection (left).

func LeftJoinInt added in v0.7.0

func LeftJoinInt(lx, rx []int) []int

LeftJoinInt finds and returns dissimilar data from the first int collection (left).

func LeftJoinInt32 added in v0.7.0

func LeftJoinInt32(lx, rx []int32) []int32

LeftJoinInt32 finds and returns dissimilar data from the first int32 collection (left).

func LeftJoinInt64 added in v0.7.0

func LeftJoinInt64(lx, rx []int64) []int64

LeftJoinInt64 finds and returns dissimilar data from the first int64 collection (left).

func LeftJoinString added in v0.7.0

func LeftJoinString(lx, rx []string) []string

LeftJoinString finds and returns dissimilar data from the first string collection (left).

func Map

func Map(arr interface{}, mapFunc interface{}) interface{}

Map manipulates an iteratee and transforms it to another type.

func MaxFloat32 added in v0.5.0

func MaxFloat32(i []float32) float32

MaxFloat32 validates the input, compares the elements and returns the maximum element in an array/slice. It accepts []float32 It returns float32

func MaxFloat64 added in v0.5.0

func MaxFloat64(i []float64) float64

MaxFloat64 validates the input, compares the elements and returns the maximum element in an array/slice. It accepts []float64 It returns float64

func MaxInt added in v0.5.0

func MaxInt(i []int) int

MaxInt validates the input, compares the elements and returns the maximum element in an array/slice. It accepts []int It returns int

func MaxInt16 added in v0.5.0

func MaxInt16(i []int16) int16

MaxInt16 validates the input, compares the elements and returns the maximum element in an array/slice. It accepts []int16 It returns int16

func MaxInt32 added in v0.5.0

func MaxInt32(i []int32) int32

MaxInt32 validates the input, compares the elements and returns the maximum element in an array/slice. It accepts []int32 It returns int32

func MaxInt64 added in v0.5.0

func MaxInt64(i []int64) int64

MaxInt64 validates the input, compares the elements and returns the maximum element in an array/slice. It accepts []int64 It returns int64

func MaxInt8 added in v0.5.0

func MaxInt8(i []int8) int8

MaxInt8 validates the input, compares the elements and returns the maximum element in an array/slice. It accepts []int8 It returns int8

func MaxString added in v0.5.0

func MaxString(i []string) string

MaxString validates the input, compares the elements and returns the maximum element in an array/slice. It accepts []string It returns string

func MinFloat32 added in v0.5.0

func MinFloat32(i []float32) float32

MinFloat32 validates the input, compares the elements and returns the minimum element in an array/slice. It accepts []float32 It returns float32

func MinFloat64 added in v0.5.0

func MinFloat64(i []float64) float64

MinFloat64 validates the input, compares the elements and returns the minimum element in an array/slice. It accepts []float64 It returns float64

func MinInt added in v0.5.0

func MinInt(i []int) int

MinInt validates the input, compares the elements and returns the minimum element in an array/slice. It accepts []int It returns int

func MinInt16 added in v0.5.0

func MinInt16(i []int16) int16

MinInt16 validates the input, compares the elements and returns the minimum element in an array/slice. It accepts []int16 It returns int16

func MinInt32 added in v0.5.0

func MinInt32(i []int32) int32

MinInt32 validates the input, compares the elements and returns the minimum element in an array/slice. It accepts []int32 It returns int32

func MinInt64 added in v0.5.0

func MinInt64(i []int64) int64

MinInt64 validates the input, compares the elements and returns the minimum element in an array/slice. It accepts []int64 It returns int64

func MinInt8 added in v0.5.0

func MinInt8(i []int8) int8

MinInt8 validates the input, compares the elements and returns the minimum element in an array/slice. It accepts []int8 It returns int8

func MinString added in v0.5.0

func MinString(i []string) string

MinString validates the input, compares the elements and returns the minimum element in an array/slice. It accepts []string It returns string

func MustSet added in v0.8.0

func MustSet(in interface{}, val interface{}, path string)

MustSet is functionally the same as Set. It panics instead of returning error. It is safe to use if the in value is well formed.

func NextPermutation added in v0.8.0

func NextPermutation(nums []int) error

NextPermutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

func NotEmpty

func NotEmpty(obj interface{}) bool

NotEmpty returns if the object is considered as non-empty or not.

func NotEqual

func NotEqual(expected interface{}, actual interface{}) bool

NotEqual returns if the two objects are not equal

func OuterJoin added in v0.7.0

func OuterJoin(lx, rx reflect.Value) reflect.Value

OuterJoin finds and returns dissimilar data from two collections.

func OuterJoinFloat32 added in v0.7.0

func OuterJoinFloat32(lx, rx []float32) []float32

OuterJoinFloat32 finds and returns dissimilar data from two float32 collections.

func OuterJoinFloat64 added in v0.7.0

func OuterJoinFloat64(lx, rx []float64) []float64

OuterJoinFloat64 finds and returns dissimilar data from two float64 collections.

func OuterJoinInt added in v0.7.0

func OuterJoinInt(lx, rx []int) []int

OuterJoinInt finds and returns dissimilar data from two int collections.

func OuterJoinInt32 added in v0.7.0

func OuterJoinInt32(lx, rx []int32) []int32

OuterJoinInt32 finds and returns dissimilar data from two int32 collections.

func OuterJoinInt64 added in v0.7.0

func OuterJoinInt64(lx, rx []int64) []int64

OuterJoinInt64 finds and returns dissimilar data from two int64 collections.

func OuterJoinString added in v0.7.0

func OuterJoinString(lx, rx []string) []string

OuterJoinString finds and returns dissimilar data from two string collections.

func Product

func Product(arr interface{}) float64

Product computes the product of the values in array.

func Prune added in v0.8.0

func Prune(in interface{}, paths []string) (interface{}, error)

Prune returns a copy of "in" that only contains fields in "paths" which are looked up using struct field name. For lookup paths by field tag instead, use funk.PruneByTag()

Example
type ExampleFoo struct {
	ExampleFooPtr *ExampleFoo `json:"example_foo_ptr"`
	Name          string      `json:"name"`
	Number        int         `json:"number"`
}

exampleFoo := ExampleFoo{
	ExampleFooPtr: &ExampleFoo{
		Name:   "ExampleFooPtr",
		Number: 2,
	},
	Name:   "ExampleFoo",
	Number: 1,
}

// prune using struct field name
res, _ := Prune(exampleFoo, []string{"ExampleFooPtr.Name", "Number"})
prunedFoo := res.(ExampleFoo)
fmt.Println(prunedFoo.ExampleFooPtr.Name)
fmt.Println(prunedFoo.ExampleFooPtr.Number)
fmt.Println(prunedFoo.Name)
fmt.Println(prunedFoo.Number)

// prune using struct json tag
res2, _ := PruneByTag(exampleFoo, []string{"example_foo_ptr.name", "number"}, "json")
prunedByTagFoo := res2.(ExampleFoo)
fmt.Println(prunedByTagFoo.ExampleFooPtr.Name)
fmt.Println(prunedByTagFoo.ExampleFooPtr.Number)
fmt.Println(prunedByTagFoo.Name)
fmt.Println(prunedByTagFoo.Number)
Output:

ExampleFooPtr
0

1
ExampleFooPtr
0

1

func PruneByTag added in v0.8.0

func PruneByTag(in interface{}, paths []string, tag string) (interface{}, error)

pruneByTag returns a copy of "in" that only contains fields in "paths" which are looked up using struct field Tag "tag".

func PtrOf

func PtrOf(itf interface{}) interface{}

PtrOf makes a copy of the given interface and returns a pointer.

func RandomInt

func RandomInt(min, max int) int

RandomInt generates a random int, based on a min and max values

func RandomString

func RandomString(n int, allowedChars ...[]rune) string

RandomString returns a random string with a fixed length

func Reduce

func Reduce(arr, reduceFunc, acc interface{}) interface{}

Reduce takes a collection and reduces it to a single value using a reduction function (or a valid symbol) and an accumulator value.

func Reverse

func Reverse(in interface{}) interface{}

Reverse transforms an array the first element will become the last, the second element will become the second to last, etc.

func ReverseBools added in v0.9.0

func ReverseBools(s []bool) []bool

ReverseBools reverses an array of bool

func ReverseFloat32

func ReverseFloat32(s []float32) []float32

ReverseFloat32 reverses an array of float32

func ReverseFloat64

func ReverseFloat64(s []float64) []float64

ReverseFloat64 reverses an array of float64

func ReverseInt

func ReverseInt(s []int) []int

ReverseInt reverses an array of int

func ReverseInt32

func ReverseInt32(s []int32) []int32

ReverseInt32 reverses an array of int32

func ReverseInt64

func ReverseInt64(s []int64) []int64

ReverseInt64 reverses an array of int64

func ReverseString

func ReverseString(s string) string

ReverseString reverses a string

func ReverseStrings

func ReverseStrings(s []string) []string

ReverseStrings reverses an array of string

func ReverseUInt added in v0.8.0

func ReverseUInt(s []uint) []uint

ReverseUInt reverses an array of int

func ReverseUInt32 added in v0.8.0

func ReverseUInt32(s []uint32) []uint32

ReverseUInt32 reverses an array of uint32

func ReverseUInt64 added in v0.8.0

func ReverseUInt64(s []uint64) []uint64

ReverseUInt64 reverses an array of uint64

func RightJoin added in v0.7.0

func RightJoin(lx, rx reflect.Value) reflect.Value

LeftJoin finds and returns dissimilar data from the second collection (right).

func RightJoinFloat32 added in v0.7.0

func RightJoinFloat32(lx, rx []float32) []float32

LeftJoinFloat32 finds and returns dissimilar data from the second float32 collection (right).

func RightJoinFloat64 added in v0.7.0

func RightJoinFloat64(lx, rx []float64) []float64

LeftJoinFloat64 finds and returns dissimilar data from the second float64 collection (right).

func RightJoinInt added in v0.7.0

func RightJoinInt(lx, rx []int) []int

LeftJoinInt finds and returns dissimilar data from the second int collection (right).

func RightJoinInt32 added in v0.7.0

func RightJoinInt32(lx, rx []int32) []int32

LeftJoinInt32 finds and returns dissimilar data from the second int32 collection (right).

func RightJoinInt64 added in v0.7.0

func RightJoinInt64(lx, rx []int64) []int64

LeftJoinInt64 finds and returns dissimilar data from the second int64 collection (right).

func RightJoinString added in v0.7.0

func RightJoinString(lx, rx []string) []string

LeftJoinString finds and returns dissimilar data from the second string collection (right).

func Set added in v0.8.0

func Set(in interface{}, val interface{}, path string) error

Set assigns in at path with value val. i.e. in.path = val in accepts types of ptr to struct, ptr to variable, slice and ptr to slice. Along the path, interface{} is supported and nil ptr is initialized to ptr to zero value of the type until the variable to be set is obtained. It returns errors when encountering along the path unknown types, uninitialized interface{} or interface{} containing struct directly (not ptr to struct).

Slice is resolved the same way in funk.Get(), by traversing each element of the slice, so that each element of the slice's corresponding field are going to be set to the same provided val. If Set is called on slice with empty path "", it behaves the same as funk.Fill()

If in is well formed, i.e. do not expect above descripted errors to happen, funk.MustSet() is a short hand wrapper to discard error return

Example
var bar Bar = Bar{
	Name: "level-0",
	Bar: &Bar{
		Name: "level-1",
		Bars: []*Bar{
			{Name: "level2-1"},
			{Name: "level2-2"},
		},
	},
}

_ = Set(&bar, "level-0-new", "Name")
fmt.Println(bar.Name)

// discard error use MustSet
MustSet(&bar, "level-1-new", "Bar.Name")
fmt.Println(bar.Bar.Name)

_ = Set(&bar, "level-2-new", "Bar.Bars.Name")
fmt.Println(bar.Bar.Bars[0].Name)
fmt.Println(bar.Bar.Bars[1].Name)
Output:

level-0-new
level-1-new
level-2-new
level-2-new

func Shard

func Shard(str string, width int, depth int, restOnly bool) []string

Shard will shard a string name

func ShortIf added in v0.8.0

func ShortIf(condition bool, a interface{}, b interface{}) interface{}

func Shuffle

func Shuffle(in interface{}) interface{}

Shuffle creates an array of shuffled values

func ShuffleBool added in v0.9.0

func ShuffleBool(a []bool) []bool

ShuffleBool creates an array of bool shuffled values using Fisher–Yates algorithm

func ShuffleFloat32

func ShuffleFloat32(a []float32) []float32

ShuffleFloat32 creates an array of float32 shuffled values using Fisher–Yates algorithm

func ShuffleFloat64

func ShuffleFloat64(a []float64) []float64

ShuffleFloat64 creates an array of float64 shuffled values using Fisher–Yates algorithm

func ShuffleInt

func ShuffleInt(a []int) []int

ShuffleInt creates an array of int shuffled values using Fisher–Yates algorithm

func ShuffleInt32

func ShuffleInt32(a []int32) []int32

ShuffleInt32 creates an array of int32 shuffled values using Fisher–Yates algorithm

func ShuffleInt64

func ShuffleInt64(a []int64) []int64

ShuffleInt64 creates an array of int64 shuffled values using Fisher–Yates algorithm

func ShuffleString

func ShuffleString(a []string) []string

ShuffleString creates an array of string shuffled values using Fisher–Yates algorithm

func ShuffleUInt added in v0.8.0

func ShuffleUInt(a []uint) []uint

ShuffleUInt creates an array of int shuffled values using Fisher–Yates algorithm

func ShuffleUInt32 added in v0.8.0

func ShuffleUInt32(a []uint32) []uint32

ShuffleUInt32 creates an array of uint32 shuffled values using Fisher–Yates algorithm

func ShuffleUInt64 added in v0.8.0

func ShuffleUInt64(a []uint64) []uint64

ShuffleUInt64 creates an array of uint64 shuffled values using Fisher–Yates algorithm

func SliceOf

func SliceOf(in interface{}) interface{}

SliceOf returns a slice which contains the element.

func Some added in v0.5.0

func Some(in interface{}, elements ...interface{}) bool

Some returns true if atleast one element is present in an iteratee.

Example
a := []string{"foo", "bar", "baz"}
fmt.Println(Some(a, "foo", "qux"))

b := "Mark Shaun"
fmt.Println(Some(b, "Marc", "Sean"))
Output:

true
false

func StringerJoin added in v0.9.0

func StringerJoin(elems []interface{ String() string }, sep string) string

StringerJoin joins an array of elements which implement the `String() string` function. Direct copy of strings.Join() with a few tweaks.

func Subset added in v0.7.0

func Subset(x interface{}, y interface{}) bool

Subset returns true if collection x is a subset of y.

func Subtract added in v0.6.0

func Subtract(x interface{}, y interface{}) interface{}

Subtract returns the subtraction between two collections.

func SubtractString added in v0.6.0

func SubtractString(x []string, y []string) []string

SubtractString returns the subtraction between two collections of string

func Sum

func Sum(arr interface{}) float64

Sum computes the sum of the values in array.

func SumFloat32

func SumFloat32(s []float32) (sum float32)

SumFloat32 sums a float32 iteratee and returns the sum of all elements

func SumFloat64

func SumFloat64(s []float64) (sum float64)

SumFloat64 sums a float64 iteratee and returns the sum of all elements

func SumInt

func SumInt(s []int) (sum int)

SumInt sums a int iteratee and returns the sum of all elements

func SumInt32

func SumInt32(s []int32) (sum int32)

SumInt32 sums a int32 iteratee and returns the sum of all elements

func SumInt64

func SumInt64(s []int64) (sum int64)

SumInt64 sums a int64 iteratee and returns the sum of all elements

func SumUInt added in v0.8.0

func SumUInt(s []uint) (sum uint)

SumUInt sums a uint iteratee and returns the sum of all elements

func SumUInt32 added in v0.8.0

func SumUInt32(s []uint32) (sum uint32)

SumUInt32 sums a uint32 iteratee and returns the sum of all elements

func SumUInt64 added in v0.8.0

func SumUInt64(s []uint64) (sum uint64)

SumUInt64 sums a uint64 iteratee and returns the sum of all elements

func Tail

func Tail(arr interface{}) interface{}

Tail gets all but the first element of array.

func ToFloat64

func ToFloat64(x interface{}) (float64, bool)

ToFloat64 converts any numeric value to float64.

func ToMap

func ToMap(in interface{}, pivot string) interface{}

ToMap transforms a collection of instances to a Map. []T => map[type of T.<pivot>]T

func ToSet added in v0.9.2

func ToSet(in interface{}) interface{}

ToSet transforms a collection of instances to a Set. []T => map[T]struct{}

func Union added in v0.9.2

func Union(collections ...interface{}) interface{}

Union returns the union between two collections.

func UnionStringMap added in v0.9.2

func UnionStringMap(x ...map[string]string) map[string]string

UnionStringMap returns the union between multiple string maps

func Uniq

func Uniq(in interface{}) interface{}

Uniq creates an array with unique values.

func UniqBool added in v0.9.0

func UniqBool(a []bool) []bool

UniqBool creates an array of bool with unique values.

func UniqBy added in v0.9.2

func UniqBy(in interface{}, mapFunc interface{}) interface{}

Uniq creates an array with unique values.

func UniqFloat32

func UniqFloat32(a []float32) []float32

UniqFloat32 creates an array of float32 with unique values.

func UniqFloat64

func UniqFloat64(a []float64) []float64

UniqFloat64 creates an array of float64 with unique values.

func UniqInt

func UniqInt(a []int) []int

UniqInt creates an array of int with unique values.

func UniqInt32

func UniqInt32(a []int32) []int32

UniqInt32 creates an array of int32 with unique values.

func UniqInt64

func UniqInt64(a []int64) []int64

UniqInt64 creates an array of int64 with unique values.

func UniqString

func UniqString(a []string) []string

UniqString creates an array of string with unique values.

func UniqUInt added in v0.8.0

func UniqUInt(a []uint) []uint

UniqUInt creates an array of uint with unique values.

func UniqUInt32 added in v0.8.0

func UniqUInt32(a []uint32) []uint32

UniqUInt32 creates an array of uint32 with unique values.

func UniqUInt64 added in v0.8.0

func UniqUInt64(a []uint64) []uint64

UniqUInt64 creates an array of uint64 with unique values.

func Values

func Values(out interface{}) interface{}

Values creates an array of the own enumerable map values or struct field values.

func WithAllowZero added in v0.9.0

func WithAllowZero() func(*options)

WithAllowZero allows zero values.

func Without added in v0.7.0

func Without(in interface{}, values ...interface{}) interface{}

Without creates an array excluding all given values.

func ZeroOf

func ZeroOf(in interface{}) interface{}

ZeroOf returns a zero value of an element.

Types

type Builder

type Builder interface {
	Chunk(size int) Builder
	Compact() Builder
	Drop(n int) Builder
	Filter(predicate interface{}) Builder
	Flatten() Builder
	FlattenDeep() Builder
	Initial() Builder
	Intersect(y interface{}) Builder
	Join(rarr interface{}, fnc JoinFnc) Builder
	Map(mapFunc interface{}) Builder
	FlatMap(mapFunc interface{}) Builder
	Reverse() Builder
	Shuffle() Builder
	Tail() Builder
	Uniq() Builder
	Without(values ...interface{}) Builder

	All() bool
	Any() bool
	Contains(elem interface{}) bool
	Every(elements ...interface{}) bool
	Find(predicate interface{}) interface{}
	ForEach(predicate interface{})
	ForEachRight(predicate interface{})
	Head() interface{}
	Keys() interface{}
	IndexOf(elem interface{}) int
	IsEmpty() bool
	Last() interface{}
	LastIndexOf(elem interface{}) int
	NotEmpty() bool
	Product() float64
	Reduce(reduceFunc, acc interface{}) interface{}
	Sum() float64
	Type() reflect.Type
	Value() interface{}
	Values() interface{}
}

Builder contains all tools which can be chained.

func Chain

func Chain(v interface{}) Builder

Chain creates a simple new go-funk.Builder from a collection. Each method call generate a new builder containing the previous result.

Example
v := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
chain := Chain(v)
lazy := LazyChain(v)

// Without builder
a := Filter(v, func(x int) bool { return x%2 == 0 })
b := Map(a, func(x int) int { return x * 2 })
c := Reverse(a)
fmt.Printf("funk.Contains(b, 2): %v\n", Contains(b, 2)) // false
fmt.Printf("funk.Contains(b, 4): %v\n", Contains(b, 4)) // true
fmt.Printf("funk.Sum(b): %v\n", Sum(b))                 // 40
fmt.Printf("funk.Head(b): %v\n", Head(b))               // 4
fmt.Printf("funk.Head(c): %v\n\n", Head(c))             // 8

// With simple chain builder
ca := chain.Filter(func(x int) bool { return x%2 == 0 })
cb := ca.Map(func(x int) int { return x * 2 })
cc := ca.Reverse()
fmt.Printf("chainB.Contains(2): %v\n", cb.Contains(2)) // false
fmt.Printf("chainB.Contains(4): %v\n", cb.Contains(4)) // true
fmt.Printf("chainB.Sum(): %v\n", cb.Sum())             // 40
fmt.Printf("chainB.Head(): %v\n", cb.Head())           // 4
fmt.Printf("chainC.Head(): %v\n\n", cc.Head())         // 8

// With lazy chain builder
la := lazy.Filter(func(x int) bool { return x%2 == 0 })
lb := la.Map(func(x int) int { return x * 2 })
lc := la.Reverse()
fmt.Printf("lazyChainB.Contains(2): %v\n", lb.Contains(2)) // false
fmt.Printf("lazyChainB.Contains(4): %v\n", lb.Contains(4)) // true
fmt.Printf("lazyChainB.Sum(): %v\n", lb.Sum())             // 40
fmt.Printf("lazyChainB.Head(): %v\n", lb.Head())           // 4
fmt.Printf("lazyChainC.Head(): %v\n", lc.Head())           // 8
Output:

func LazyChain

func LazyChain(v interface{}) Builder

LazyChain creates a lazy go-funk.Builder from a collection. Each method call generate a new builder containing a method generating the previous value. With that, all data are only generated when we call a tailling method like All or Find.

Example
us := updatingStruct{}
chain := Chain(us.x).
	Map(func(x int) float64 { return float64(x) * 2.5 })
lazy := LazyChain(us.x).
	Map(func(x int) float64 { return float64(x) * 2.5 })
lazyWith := LazyChainWith(us.Values).
	Map(func(x int) float64 { return float64(x) * 2.5 })

fmt.Printf("chain.Sum(): %v\n", chain.Sum())         // 0
fmt.Printf("lazy.Sum(): %v\n", lazy.Sum())           // 0
fmt.Printf("lazyWith.Sum(): %v\n\n", lazyWith.Sum()) // 0

us.x = append(us.x, 2)
fmt.Printf("chain.Sum(): %v\n", chain.Sum())         // 0
fmt.Printf("lazy.Sum(): %v\n", lazy.Sum())           // 0
fmt.Printf("lazyWith.Sum(): %v\n\n", lazyWith.Sum()) // 5

us.x = append(us.x, 10)
fmt.Printf("chain.Sum(): %v\n", chain.Sum())         // 0
fmt.Printf("lazy.Sum(): %v\n", lazy.Sum())           // 0
fmt.Printf("lazyWith.Sum(): %v\n\n", lazyWith.Sum()) // 30
Output:

func LazyChainWith

func LazyChainWith(generator func() interface{}) Builder

LazyChainWith creates a lazy go-funk.Builder from a generator. Like LazyChain, each method call generate a new builder containing a method generating the previous value. But, instead of using a collection, it takes a generator which can generate values. With LazyChainWith, to can create a generic pipeline of collection transformation and, throw the generator, sending different collection.

type JoinFloat32Fnc added in v0.7.0

type JoinFloat32Fnc func(lx, rx []float32) []float32

type JoinFloat64Fnc added in v0.7.0

type JoinFloat64Fnc func(lx, rx []float64) []float64

type JoinFnc added in v0.7.0

type JoinFnc func(lx, rx reflect.Value) reflect.Value

type JoinInt32Fnc added in v0.7.0

type JoinInt32Fnc func(lx, rx []int32) []int32

type JoinInt64Fnc added in v0.7.0

type JoinInt64Fnc func(lx, rx []int64) []int64

type JoinIntFnc added in v0.7.0

type JoinIntFnc func(lx, rx []int) []int

type JoinStringFnc added in v0.7.0

type JoinStringFnc func(lx, rx []string) []string

type Tuple

type Tuple struct {
	Element1 interface{}
	Element2 interface{}
}

Tuple is the return type of Zip

func Zip

func Zip(slice1 interface{}, slice2 interface{}) []Tuple

Zip returns a list of tuples, where the i-th tuple contains the i-th element from each of the input iterables. The returned list is truncated in length to the length of the shortest input iterable.

Jump to

Keyboard shortcuts

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