lo

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

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

Go to latest
Published: Jun 23, 2016 License: Apache-2.0 Imports: 2 Imported by: 0

README

#lo

author: Mparaiso mparaiso@online.fr

copyrights 2015 Mparaiso

license: Apache License 2.0

Build Status GoDoc

A port of lodash and underscore in golang.

lo allows Go developers to work efficiently with collections in Go by providing generic functional programming methods, such as map, reduce and filter, that work on slices and arrays of any types. lo is coded in Go.

Install it:

go get github.com/mparaiso/lodash-go

Implemented functions

  • Map
  • Reduce
  • Filter
  • Union
  • Intersection
  • Xor
  • Difference
  • IndexOf

Examples

Count words


	package main
	
	import(
		"fmt"
		"github.com/Mparaiso/lodash-go"
	)
	
	func Main(){
		// Counting words
		const words=`Lorem ipsum nascetur,
			nascetur adipiscing. Aenean commodo nascetur.
            Aenean nascetur commodo ridiculus nascetur,
            commodo ,nascetur consequat.`

	    var result map[string]int
		err:=lo.In(strings.Split(words," ")).
			Map(func(word string)string{
			return strings.Trim(strings.Trim(word,"\n\t "),".,!")
		}).
			Filter(func(word string)bool{
			return word!=""
		}).
			Reduce(func(Map map[string]int,word string)map[string]int{
			Map[word] = Map[word]+1
			return Map
		},map[string]int{}).
			Out(&result)
		fmt.Println(err)
		fmt.Println(result["nascetur"])
		fmt.Println(result["commodo"])
		
	    // Output:
		// <nil>
		// 6
		// 3
	}

Map Filter Reduce to calculate an bill


	package main
	
	import(
		"fmt"
		"github.com/Mparaiso/lodash-go"
	)
	
	func Main(){
		var total int
		type Order struct{
			Product string
			Quantity int
			UnitPrice int
			InStock bool
		}
		orders:=[]Order{
			{"Iphone", 2, 500,true}, 
			{"Graphic card", 1, 250,true}, 
			{"Flat screen", 3, 600,true},
			{"MacBook White",2,400,false},
			{"Ipad air", 5, 200,true},
		}
		err:=lo.In(orders).
			Filter(func(order Order)bool{
				return order.InStock
			}).
			Map(func(order Order,index int)int{
				return order.Quantity * order.UnitPrice
			}).
			Reduce(func(total int,subtotal int)int{
				return total + subtotal
			},0).
			Out(total)
			
		fmt.Print(err,total)
		
		// Output:
		// <nil> 4050
	}

Difference between 2 slices

	package main
	
	import(
		"fmt"
		"github.com/Mparaiso/lodash-go"
	)
	
	func Main(){
	
		var difference []string
		err := lo.Difference([]string{"a", "b", "c", "d"}, []string{"a", "c", "x"}, &difference)
		fmt.Println(err)
		fmt.Println(difference)
		
		// Output:
		// <nil>
		// [b d]
	}

Filter out odd numbers

	package main
	
	import(
		"fmt"
		"github.com/mparaiso/lodash-go"
	)
	
	func Main(){
		var evenNumbers []int
		err := lo.Filter([]int{0, 1, 2, 3, 4}, func(element int) bool {
			return element % 2 == 0
		}, &evenNumbers)
		
		fmt.Println(err)
		fmt.Println(evenNumbers)
		
		// Output:
		// <nil>
		// [0 2 4]
	}

Compute the mean of an array of integers

	package main

	import "github.com/Mparaiso/lodash-go"
	import "fmt"
		
	func Main(){
		var mean int
		err := lo.Reduce([]int{10, 20, 30}, func(result int, element int, index int, collection []int) int {
			if l := len(collection); l-1 == index {
				return (result + element) / l
			} else {
		        return result + element
			}
		}, 0, &mean)
		
		fmt.Println(mean)
		fmt.Println(err)
		
		// Output:
		// 20
		// <nil>
	}

Grouping adults by country using a pipeline

	package main
	
	import "github.com/mparaiso/lodash-go" 
	import "fmt"
	
	func Main(){
		// Group people by country
		// Demonstrates the use of Reduce to transform an collection
		// into a map
		type Person struct {
	   		Name    string
			Country string
			Age     int
	   	}
				
	    var adultPeopleByCountry map[string]int
		err := lo.In([]Person{
			{"John", "France", 18},
			{"Jane", "England", 16},
			{"Jack", "France", 20},
			{"Anna", "Spain", 19},
			{"Eduardo", "Spain", 30},
			{"Michel", "France", 12}}).
			Filter(func(person Person) bool { return person.Age >= 18 }).
			Reduce(func(list map[string]int, person Person) map[string]int {
				list[person.Country] = list[person.Country] + 1
				return list
			}, map[string]int{}).
			Out(&adultPeopleByCountry)
		
		fmt.Println(err)
		fmt.Println(adultPeopleByCountry["France"])
		fmt.Println(adultPeopleByCountry["Spain"])
		fmt.Println(adultPeopleByCountry["England"])
		
		// Output:
		// <nil>
		// 2
		// 2
		// 0
	}

Using a pipeline to compute the sum of all people in countries

	package main
	
	import "github.com/Mparaiso/lodash-go"
	import "fmt"
	
	func Main(){
		type Country struct {
			Name       string
		    Population int
		}
		var total int
		err := lo.In([]Country{{"France", 1000}, {"Spain", 5000}}).
			Map(func(country Country) int { return country.Population }).
			Reduce(func(total int, count int) int { return total + count }, 0).
			Out(&total)
		
		fmt.Println(err)
		fmt.Println(total)
		
		// Output:
		// <nil>
		// 6000
	}

Documentation

Overview

Example
// Counting words
const words = `Lorem ipsum nascetur,
            nascetur adipiscing. Aenean commodo nascetur.
            Aenean nascetur commodo ridiculus nascetur,
            commodo ,nascetur consequat.`

var result map[string]int
err := lo.In(strings.Split(words, " ")).
	Map(func(word string) string {
		return strings.Trim(strings.Trim(word, "\n\t "), ".,!")
	}).
	Filter(func(word string) bool {
		return word != ""
	}).
	Reduce(func(Map map[string]int, word string) map[string]int {
		Map[word] = Map[word] + 1
		return Map
	}, map[string]int{}).
	Out(&result)
fmt.Println(err)
fmt.Println(result["nascetur"])
fmt.Println(result["commodo"])
Output:

<nil>
6
3

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Difference

func Difference(in Collection, values Collection, out Collection) error

Difference creates an array excluding all provided values

Example
var difference []string
err := lo.Difference([]string{"a", "b", "c", "d"}, []string{"a", "c", "x"}, &difference)
fmt.Println(err)
fmt.Println(difference)
Output:

<nil>
[b d]

func Filter

func Filter(in Collection, predicate Function, out Pointer) error
Example
var evenNumbers []int
err := lo.Filter([]int{0, 1, 2, 3, 4}, func(element int) bool {
	return element%2 == 0
}, &evenNumbers)
fmt.Println(err)
fmt.Println(evenNumbers)
Output:

<nil>
[0 2 4]

func GroupBy

func GroupBy(in Collection, function Function, out Pointer) error
Example
// Group people by country

type Person struct {
	Name    string
	Country string
}
var group map[string][]Person
err := lo.GroupBy([]Person{
	{"John", "France"},
	{"Jack", "Ireland"},
	{"Igor", "Germany"},
	{"Anna", "Germany"},
	{"Louise", "France"},
}, func(person Person) (string, Person) {
	return person.Country, person
}, &group)
fmt.Println(err)
fmt.Println(group["Germany"])
fmt.Println(group["Ireland"])
Output:

<nil>
[{Igor Germany} {Anna Germany}]
[{Jack Ireland}]

func IndexOf

func IndexOf(collection Collection, element Any, start int) (int, error)

IndexOf returns the index of a value in the array from its begining, returns -1 if not found

func Intersection

func Intersection(in Collection, values Collection, out Collection) error

Intersection creates an array of unique values in all provided arrays

Example
var intersection []int
err := lo.Intersection([]int{1, 2, 3, 4}, []int{0, 2, 4, 5}, &intersection)
fmt.Println(err)
fmt.Println(intersection)
// Ouput:
// <nil>
// [2 4]
Output:

func IsCollection

func IsCollection(value Any) bool

func IsFunction

func IsFunction(f Function) bool

IsFunction returns true if f is a function

func IsPointer

func IsPointer(value Any) bool

func Map

func Map(collection Collection, function Function, result Pointer) error

Map maps a collection to a result by passing each element of the collection to a function

Example
var result []int
err := lo.Map([]int{2, 3, 4}, func(element int) int { return element * 2 }, &result)
fmt.Println(err)
fmt.Println(result)
Output:

<nil>
[4 6 8]
Example (Second)
type Data struct {
	Name  string
	Index int
}
var result2 []Data
err := lo.Map([]string{"John", "Jane", "Jack"}, func(element string, index int) Data {
	return Data{element, index}
}, &result2)
fmt.Println(err)
fmt.Println(result2)
Output:

<nil>
[{John 0} {Jane 1} {Jack 2}]
Example (Third)
// The function mapper can return an error as a second argument,
// which will be returned by lo.Map
var result []int
err := lo.Map([]bool{true, false, true}, func(element bool, index int, collection []bool) (int, error) {
	if !element {
		return 0, fmt.Errorf("Elements shouldn't be false, got '%v' at index '%d' for collection '%v'", element, index, collection)
	}
	return index, nil
}, &result)
fmt.Println(err)
Output:

Elements shouldn't be false, got 'false' at index '1' for collection '[true false true]'

func Reduce

func Reduce(collection Collection, function Function, initial Any, resultPointer Pointer) error

Reduce returns a value from an array by applying a reducer function to each element of an array. That value can be anything

Example

ExampleReduce shows how to use lo.Reduce to compute the mean of an array of number

// Compute the mean of an array of integers
var mean int
err := lo.Reduce([]int{10, 20, 30}, func(result int, element int, index int, collection []int) int {
	if l := len(collection); l-1 == index {
		return (result + element) / l
	} else {
		return result + element
	}
}, 0, &mean)
fmt.Println(mean)
fmt.Println(err)
Output:

20
<nil>
Example (Second)
// Comput the sum of an array of integers
var sum int
lo.Reduce([]int{1, 2, 3, 4}, func(result int, element int) int { return result + element }, 0, &sum)
fmt.Print(sum)
Output:

10

func Union

func Union(in Collection, values Collection, out Pointer) error

Union outputs a collection that holds unique values of in and values collections

Example
// Compute the union of 2 slices
var union []string
err := lo.Union([]string{"a", "b", "c", "d", "e"},
	[]string{"a", "c", "g", "x", "e"},
	&union)
fmt.Println(err)
fmt.Println(union)
Output:

<nil>
[a b c d e g x]

func Unique

func Unique(in Collection, out Pointer) error

Unique filters remove duplicate values from an array

Example
var uniqueValues []string
err := lo.Unique([]string{"a", "e", "a", "c", "b", "d"}, &uniqueValues)
fmt.Println(err)
fmt.Println(uniqueValues)
Output:

<nil>
[a e c b d]

func Xor

func Xor(in Collection, values Collection, out Pointer) error

Xor creates an array that is the symmetric difference of the provided arrays.

Example
// Compute the symetrical difference between 2 collections of the same type
var xor []string
err := lo.Xor([]string{"a", "b", "c", "d"}, []string{"b", "c", "d", "e", "f"}, &xor)
fmt.Println(err)
fmt.Println(xor)
Output:

<nil>
[a e f]

Types

type Any

type Any interface{}

Any is purely semantic

type Collection

type Collection interface{}

type ErrorInterface

type ErrorInterface interface {
	Error() string
}

type Function

type Function interface{}

Function is purely semantic

type IncorrectInputParameterArityError

type IncorrectInputParameterArityError string

func IncorrectInputParameterArity

func IncorrectInputParameterArity(format string, arguments ...interface{}) IncorrectInputParameterArityError

func (IncorrectInputParameterArityError) Error

type IncorrectInputParameterTypeError

type IncorrectInputParameterTypeError string

IncorrectInputParameterTypeError represent a error triggered when an input parameter passed to a function is not the right type

func IncorrectInputParameterType

func IncorrectInputParameterType(format string, arguments ...interface{}) IncorrectInputParameterTypeError

IncorrectInputParameterType returns an IncorrectInputParameterTypeError

func (IncorrectInputParameterTypeError) Error

type IncorrectOutputParameterArityError

type IncorrectOutputParameterArityError string

func IncorrectOutputParameterArity

func IncorrectOutputParameterArity(format string, arguments ...interface{}) IncorrectOutputParameterArityError

func (IncorrectOutputParameterArityError) Error

type IncorrectOutputParameterTypeError

type IncorrectOutputParameterTypeError string

IncorrectOutputParameterTypeError represent a error triggered when a value type is not of the same type as an output paramater type

func IncorrectOutputParameterType

func IncorrectOutputParameterType(format string, arguments ...interface{}) IncorrectOutputParameterTypeError

IncorrectOutputParameterType returns an IncorrectOutputParameterTypeError

func (IncorrectOutputParameterTypeError) Error

type NotACollectionError

type NotACollectionError string

NotASliceError signals that a value isn't a slice or an array

func NotACollection

func NotACollection(format string, arguments ...interface{}) NotACollectionError

NotASlice returns a NotASliceError

func (NotACollectionError) Error

func (err NotACollectionError) Error() string

Error returns a string

type NotAFunctionError

type NotAFunctionError string

func NotAFunction

func NotAFunction(format string, arguments ...interface{}) NotAFunctionError

func (NotAFunctionError) Error

func (err NotAFunctionError) Error() string

Error returns a string

type NotAPointerError

type NotAPointerError string

NotAPointerError is an error used to signal that a argument passed to a function is not a pointer

func NotPointer

func NotPointer(format string, arguments ...interface{}) NotAPointerError

func (NotAPointerError) Error

func (err NotAPointerError) Error() string

Error returns a string

type NotAssignableError

type NotAssignableError string

func NotAssignable

func NotAssignable(format string, arguments ...interface{}) NotAssignableError

func (NotAssignableError) Error

func (err NotAssignableError) Error() string

Error returns a string

type Pipeline

type Pipeline struct {
	Value Any
	Queue []func() error
}
Example
// Error while queued operations are performed

var result interface{}
err := lo.In([]string{"a"}).
	Filter(func(element string) (bool, error) {
		return false, fmt.Errorf("Something went wrong")
	}).Out(&result)
fmt.Println(err)
Output:

At step 0 : Something went wrong

func In

func In(collection Collection) *Pipeline

func (*Pipeline) Difference

func (pipeline *Pipeline) Difference(collection Collection) *Pipeline

func (*Pipeline) Filter

func (pipeline *Pipeline) Filter(predicate Function) *Pipeline

func (*Pipeline) Intersection

func (pipeline *Pipeline) Intersection(values Collection) *Pipeline

func (*Pipeline) Map

func (pipeline *Pipeline) Map(function Function) *Pipeline
Example
// Compute the sum of all countries people
type Country struct {
	Name       string
	Population int
}
var total int
err := lo.In([]Country{{"France", 1000}, {"Spain", 5000}}).
	Map(func(country Country) int { return country.Population }).
	Reduce(func(total int, count int) int { return total + count }, 0).
	Out(&total)
fmt.Println(err)
fmt.Println(total)
Output:

<nil>
6000

func (*Pipeline) Out

func (pipeline *Pipeline) Out(out Pointer) error

func (*Pipeline) Reduce

func (pipeline *Pipeline) Reduce(function Function, initial Any) *Pipeline
Example
// Group people by country
// Demonstrates the use of Reduce to transform an collection
// into a map
type Person struct {
	Name    string
	Country string
	Age     int
}

var adultPeopleByCountry map[string]int
err := lo.In([]Person{
	{"John", "France", 18},
	{"Jane", "England", 16},
	{"Jack", "France", 20},
	{"Anna", "Spain", 19},
	{"Eduardo", "Spain", 30},
	{"Michel", "France", 12}}).
	Filter(func(person Person) bool { return person.Age >= 18 }).
	Reduce(func(list map[string]int, person Person) map[string]int {
		list[person.Country] = list[person.Country] + 1
		return list
	}, map[string]int{}).
	Out(&adultPeopleByCountry)

fmt.Println(err)
fmt.Println(adultPeopleByCountry["France"])
fmt.Println(adultPeopleByCountry["Spain"])
fmt.Println(adultPeopleByCountry["England"])
Output:

<nil>
2
2
0

func (*Pipeline) Union

func (pipeline *Pipeline) Union(values Collection) *Pipeline

func (*Pipeline) Unique

func (pipeline *Pipeline) Unique() *Pipeline

func (*Pipeline) Xor

func (pipeline *Pipeline) Xor(values Collection) *Pipeline

type Pointer

type Pointer interface{}

Pointer is purely semantic

Jump to

Keyboard shortcuts

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