underscore

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2024 License: MIT Imports: 3 Imported by: 20

README

_Underscore

License Go version Go report test coverage

underscore

underscore is a Go library providing useful functional programming helpers without extending any built-in objects.

It is mostly a port from the underscore.js library based on generics brought by Go 1.18.

Usage

📚 Follow this link for the documentation.

Install the library using

go get github.com/rjNemo/underscore@0.4.0

Please check out the examples to see how to use the library.

package main

import (
 "fmt"
 u "github.com/rjNemo/underscore"
)

func main() {
 numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
 // filter even numbers from the slice
 evens := u.Filter(numbers, func(n int) bool { return n%2 == 0 })
 // square every number in the slice
 squares := u.Map(evens, func(n int) int { return n * n })
 // reduce to the sum
 res := u.Reduce(squares, func(n, acc int) int { return n + acc }, 0)

 fmt.Println(res) // 120
}

Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

Prerequisites

You need at least go1.18 for development. The project is shipped with a Dockerfile based on go1.18.

If you prefer local development, navigate to the official download page and install version 1.18 or beyond.

Installing

First clone the repository

git clone https://github.com/rjNemo/underscore.git

Install dependencies

go mod download

And that's it.

Tests

To run the unit tests, you can simply run:

make test

Functions

underscore provides many of functions that support your favorite functional helpers

Collections
  • All
  • Any
  • Contains (only numerics values at the moment)
  • Each
  • Filter
  • Flatmap
  • GroupBy
  • Find
  • Map
  • Max
  • Min
  • Partition
  • Reduce
Pipe

Calling NewPipe will cause all future method calls to return wrapped values. When you've finished the computation, call Value to retrieve the final value.

Methods not returning a slice such as Reduce, All, Any, will break the Chain and return Value instantly.

Built With

  • Go - Build fast, reliable, and efficient software at scale

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

  • Ruidy - Initial work - Ruidy

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Acknowledgments

This project is largely inspired by Underscore.js library. Check out the original project if you don't already know it.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All[T any](values []T, predicate func(T) bool) bool

All returns true if all the values in the slice pass the predicate truth test. Short-circuits and stops traversing the slice if a false element is found.

func Any

func Any[T any](values []T, predicate func(T) bool) bool

Any returns true if any of the values in the slice pass the predicate truth test. Short-circuits and stops traversing the slice if a true element is found.

func Contains

func Contains[T comparable](values []T, value T) bool

Contains returns true if the value is present in the slice

func Count added in v0.6.0

func Count[T any](slice []T, predicate func(T) bool) int

Count returns the number of elements in the slice that satisfy the predicate. example: Count([]int{1,2,3,4,5}, func(n int) bool { return n%2 == 0 }) // 2

func Difference

func Difference[T comparable](slice, other []T) []T

Difference Returns a copy of the array with all instances of the values that are not present in the other array.

func Drop

func Drop[T any](values []T, index int) (rest []T)

Drop returns the rest of the elements in a slice. Pass an index to return the values of the slice from that index onward.

func Each

func Each[T any](values []T, action func(T)) []T

Each iterates over a slice of elements, yielding each in turn to an action function. Returns the slice for piping.

func Filter

func Filter[T any](values []T, predicate func(T) bool) (res []T)

Filter looks through each value in the slice, returning a slice of all the values that pass a truth test (predicate).

func Find

func Find[T any](values []T, predicate func(T) bool) (res T, err error)

Find looks through each value in the slice, returning the first one that passes a truth test (predicate), or the default value for the type and an error if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire slice.

func Flatmap added in v0.5.0

func Flatmap[T any](values []T, mapper func(n T) []T) []T

Flatmap flatten the input slice element into the new slice. FlatMap maps every element with the help of a mapper function, then flattens the input slice element into the new slice.

func GroupBy

func GroupBy[K comparable, V any](values []V, f func(V) K) map[K][]V

GroupBy splits a slice into a map[K][]V grouped by the result of the iterator function.

func Intersection

func Intersection[T comparable](a, b []T) (res []T)

Intersection computes the list of values that are the intersection of all the slices. Each value in the result is present in each of the slices.

func JoinProject added in v0.5.0

func JoinProject[L, R, O any, S comparable](
	left []L,
	right []R,
	leftSelector func(L) S,
	rightSelector func(R) S,
	projection func(Tuple[L, []R]) O) (results []O)

Joins two slices together and returns a []O where O is defined by the output of your projection function The selectors allow you to pick the keys from your structure to use as the join keys While the projection functions allows you to reformat joined datasets (Tuple of [T, []P]) into your own struct or type

func Last

func Last[T any](values []T) T

Last returns the last element of the slice

func Map

func Map[T, P any](values []T, transform func(T) P) []P

Map produces a new slice of values by mapping each value in the slice through a transform function.

func Max

func Max[T constraints.Ordered](values []T) T

Max returns the maximum value in the slice. This function can currently only compare numbers reliably. This function uses operator <.

func Min

func Min[T constraints.Ordered](values []T) T

Min returns the minimum value in the slice. This function can currently only compare numbers reliably. This function uses operator <.

func OrderBy added in v0.5.0

func OrderBy[T any](list []T, predicate func(T, T) bool) []T

Orders a slice by a field value within a struct, the predicate allows you to pick the fields you want to orderBy. Use > for ASC or < for DESC

func (left Person, right Person) bool { return left.Age > right.Age }

func Partition

func Partition[T any](values []T, predicate func(T) bool) ([]T, []T)

Partition splits the slice into two slices: one whose elements all satisfy predicate and one whose elements all do not satisfy predicate.

func Range added in v0.5.0

func Range(start int, end int) (result []int)

Creates a sequence of numbers, i.e. u.Range(0, 3) = [0 1 2 3], while u.Range(3, 0) = [3 2 1 0]

func Reduce

func Reduce[T, P any](values []T, reduction func(T, P) P, acc P) P

Reduce combine a list of values into a single value. acc is the initial state, and each successive step of it should be returned by the reduction function.

func SortSliceASC added in v0.7.0

func SortSliceASC[T constraints.Ordered](s []T)

sort any slice ASENDING

func SortSliceDESC added in v0.7.0

func SortSliceDESC[T constraints.Ordered](s []T)

sort any slice DESCENDING

func Sum

func Sum[T constraints.Ordered](values []T) (sum T)

Sum adds elements of the slice.

func SumMap added in v0.5.0

func SumMap[T any, R constraints.Ordered](list []T, selector func(T) R) (sum R)

Sums the values you select from your struct, basically a sort cut instead of having to perform a u.Map followed by a u.Sum

func Ternary

func Ternary[T any](condition bool, pos, neg T) T

func ToPointer added in v0.7.0

func ToPointer[T any](in T) *T

Convert values to pointers

Instead of: v := "value" MyPointerVar = &v

Or v1 := "value1" v2 := 100

obj := Obj{
	Field1: &v,
	Field2: &v2,
}

Use: MyPointerVar = ToPointer("value")

func Unique

func Unique[T comparable](values []T) (uniques []T)

Types

type Err

type Err[T any] struct{ Err error }

Err is the Result that represents failure. It implements the error interface

func (Err[T]) Error

func (e Err[T]) Error() string

func (Err[T]) IsSuccess

func (e Err[T]) IsSuccess() bool

func (Err[T]) ToValue

func (e Err[T]) ToValue() (*T, error)

type Ok

type Ok[T any] struct {
	Value *T
}

Ok is the Result that represents success.

func (Ok[T]) IsSuccess

func (o Ok[T]) IsSuccess() bool

func (Ok[T]) ToValue

func (o Ok[T]) ToValue() (*T, error)

type Pipe

type Pipe[T constraints.Ordered] struct {
	Value []T
}

func NewPipe

func NewPipe[T constraints.Ordered](value []T) Pipe[T]

NewPipe starts a Pipe. All future method calls will return Pipe structs. When you've finished the computation, call Value to retrieve the final value.

Methods not returning a slice such as Reduce, All, Any, will break the Pipe and return Value instantly.

func (Pipe[T]) All

func (c Pipe[T]) All(predicate func(T) bool) bool

All returns true if all the values in the slice pass the predicate truth test. Short-circuits and stops traversing the slice if a false element is found. Breaks the Pipe.

func (Pipe[T]) Any

func (c Pipe[T]) Any(predicate func(T) bool) bool

Any returns true if any of the values in the slice pass the predicate truth test. Short-circuits and stops traversing the slice if a true element is found. Breaks the Pipe.

func (Pipe[T]) Contains

func (c Pipe[T]) Contains(value T) bool

Contains returns true if the value is present in the slice and breaks the Pipe.

func (Pipe[T]) Each

func (c Pipe[T]) Each(action func(T))

Each iterates over a slice of elements, yielding each in turn to an action function. Breaks the Pipe.

func (Pipe[T]) Filter

func (c Pipe[T]) Filter(predicate func(n T) bool) Pipe[T]

Filter looks through each value in the slice, returning a slice of all the values that pass a truth test (predicate).

func (Pipe[T]) Find

func (c Pipe[T]) Find(predicate func(n T) bool) (T, error)

Find looks through each value in the slice, returning the first one that passes a truth test (predicate), or the default value for the type and an error if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire slice. Breaks the Pipe.

func (Pipe[T]) Map

func (c Pipe[T]) Map(transform func(n T) T) Pipe[T]

Map produces a new slice of values by mapping each value in the slice through a transform function.

TODO: Move from T to P.

func (Pipe[T]) Max

func (c Pipe[T]) Max() T

Max returns the maximum value in the slice. This function can currently only compare numbers reliably. This function uses operator <. Breaks the Pipe.

func (Pipe[T]) Min

func (c Pipe[T]) Min() T

Min returns the minimum value in the slice. This function can currently only compare numbers reliably. This function uses operator <. Breaks the Pipe.

func (Pipe[T]) Partition

func (c Pipe[T]) Partition(predicate func(T) bool) ([]T, []T)

Partition splits the slice into two slices: one whose elements all satisfy predicate and one whose elements all do not satisfy predicate. Breaks the Pipe.

func (Pipe[T]) Reduce

func (c Pipe[T]) Reduce(reducer func(n, acc T) T, acc T) T

Reduce combine a list of values into a single value and breaks the Pipe. acc is the initial state, and each successive step of it should be returned by the reduction function.

type Result

type Result[T any] interface {
	ToValue() (*T, error)
	IsSuccess() bool
	// contains filtered or unexported methods
}

Result represent the outcome of an operation where failure is possible

func ToResult

func ToResult[T any](value *T, err error) Result[T]

type Tuple added in v0.5.0

type Tuple[L, R any] struct {
	Left  L
	Right R
}

func Join added in v0.5.0

func Join[T, P any, S comparable](
	left []T,
	right []P,
	leftSelector func(T) S,
	rightSelector func(P) S) []Tuple[T, []P]

Joins two slices together and returns a Tuple of [T, []P], the selectors allow you to pick the keys you want to use from your struct's to join the sets together

func Zip added in v0.5.0

func Zip[L any, R any](left []L, right []R) []Tuple[L, R]

Zips two slices togther so all the elements of left slice are attached to the corresponding elements of the right slice, i.e. [one two three] [1 2 3 4] = [{one, 1} {two, 2} {three, 3}] the returned data will be the size of the smallest slice

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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