mfr

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2022 License: MIT Imports: 0 Imported by: 0

README

mfr

(Immutable) Map/Filter/Reduce functions (+ friends).

Disclaimer: if you need as much performance as possible, this library is not for you.

Install

$ go get github.com/bnert/mfr

Note: must have go1.18 installed.

Example Usage (Map/Filter/Reduce)

package main

import (
  "fmt"
  "github.com/bnert/mfr"
)

type Data struct {
  Value int `json:"value"`
}

func main() {
  d1 := []Data{
    Data{Value: 0},
    Data{Value: 1},
    Data{Value: 2},
    Data{Value: 3},
    Data{Value: 4},
  }

  // Map to a different type
  d2 := mfr.Map[Data, int](d1, func(ctx mfr.Ctx[Data]) int) []int {
    return ctx.Item.Value * 3
  })

  d3 := mfr.Filter[Data](d2, func(ctx mfr.Ctx[Data]) bool) []Data {
    return ctx.Item % 2 == 0
  })

  sum := mfr.Reduce[int, int](d3, 0, func(ctx mfr.Ctx[int], acc int) int {
    return ctx.Current + ctx.Item
  })

  // Prints:
  // Reduced even sum: 18
  fmt.Println("Reduced evens sum:", sum)
}

Please see examples/ and tests/ directory for other examples of how this library can be used to write (somewhat) functional go.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EntriesToMap

func EntriesToMap[K comparable, V any](entries []Entry[K, V]) map[K]V

EntriesToMap converts an array of entries back into a map

func Filter

func Filter[T any](s []T, fn func(Ctx[T]) bool) []T

Filter returns an array of items for which the provided function returns true.

func ForEach

func ForEach[T any](s []T, fn func(Ctx[T]))

ForEach iterates over each item of the provided array, calling the provided function for each item.

func Map

func Map[From any, To any](s []From, fn func(Ctx[From]) To) []To

Map maps one type to another, via the transform function provided.

func Reduce

func Reduce[From any, To any](s []From, init To, fn func(Ctx[From], To) To) To

Reduce reduces and/or collects from an array to a target type, from an initial value.

Types

type Ctx

type Ctx[T any] struct {
	// Array is the
	Array   []T
	Index   int
	IsFirst bool
	IsLast  bool
	Item    T
}

Ctx is the context passed to Map/Filter/Reduce/ForEach

type Entry

type Entry[K any, V any] struct {
	Key   K
	Value V
}

Entry is a struct representation of an entry in a map.

func EntriesFromMap

func EntriesFromMap[K comparable, V any](m map[K]V) []Entry[K, V]

EntriesFromMap returns an array of entries, enabling maps to be used with Map/Reduce/Filter/ForEach

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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