pax_global_header00006660000000000000000000000064147031653470014524gustar00rootroot0000000000000052 comment=225ca193fb517574f3a408a8f44628e674555643 go-algorithms-0.4.0/000077500000000000000000000000001470316534700143015ustar00rootroot00000000000000go-algorithms-0.4.0/LICENSE000066400000000000000000000027431470316534700153140ustar00rootroot00000000000000 Copyright (c) 2024, Cristian Maglie. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. go-algorithms-0.4.0/arguments.go000066400000000000000000000011721470316534700166360ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f import "fmt" // Must should be used to wrap a call to a function returning a value and an error. // Must returns the value if the errors is nil, or panics otherwise. func Must[T any](val T, err error) T { if err != nil { panic(err.Error()) } return val } // Assert panics if condition is false. func Assert(condition bool, msg string, args ...any) { if !condition { panic(fmt.Sprintf(msg, args...)) } } go-algorithms-0.4.0/arguments_test.go000066400000000000000000000011571470316534700177000ustar00rootroot00000000000000package f_test import ( "fmt" "testing" "github.com/stretchr/testify/assert" f "go.bug.st/f" ) func TestMust(t *testing.T) { t.Run("no error", func(t *testing.T) { assert.Equal(t, 12, f.Must(12, nil)) }) t.Run("error", func(t *testing.T) { want := fmt.Errorf("this is an error") assert.PanicsWithValue(t, want.Error(), func() { f.Must(0, want) }) }) } func TestAssert(t *testing.T) { t.Run("true", func(_ *testing.T) { f.Assert(true, "should not panic") }) t.Run("false", func(t *testing.T) { assert.PanicsWithValue(t, "should panic", func() { f.Assert(false, "should panic") }) }) } go-algorithms-0.4.0/channels.go000066400000000000000000000020561470316534700164260ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f import "sync" // DiscardCh consumes all incoming messages from the given channel until it's closed. func DiscardCh[T any](ch <-chan T) { for range ch { } } // Future is an object that holds a result value. The value may be read and // written asynchronously. type Future[T any] struct { lock sync.Mutex set bool cond *sync.Cond value T } // Send a result in the Future. Threads waiting for result will be unlocked. func (f *Future[T]) Send(value T) { f.lock.Lock() defer f.lock.Unlock() f.set = true f.value = value if f.cond != nil { f.cond.Broadcast() f.cond = nil } } // Await for a result from the Future, blocks until a result is available. func (f *Future[T]) Await() T { f.lock.Lock() defer f.lock.Unlock() for !f.set { if f.cond == nil { f.cond = sync.NewCond(&f.lock) } f.cond.Wait() } return f.value } go-algorithms-0.4.0/channels_test.go000066400000000000000000000014471470316534700174700ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f_test import ( "testing" "time" "github.com/stretchr/testify/require" f "go.bug.st/f" ) func TestFutures(t *testing.T) { { var futureInt f.Future[int] go func() { time.Sleep(100 * time.Millisecond) futureInt.Send(5) }() require.Equal(t, 5, futureInt.Await()) go func() { require.Equal(t, 5, futureInt.Await()) }() go func() { require.Equal(t, 5, futureInt.Await()) }() } { var futureInt f.Future[int] futureInt.Send(5) require.Equal(t, 5, futureInt.Await()) require.Equal(t, 5, futureInt.Await()) require.Equal(t, 5, futureInt.Await()) } } go-algorithms-0.4.0/doc.go000066400000000000000000000005611470316534700153770ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // /* Package f is a golang library implementing some basic algorithms. The canonical import for this library is go.bug.st/f: import "go.bug.st/f" */ package f go-algorithms-0.4.0/go.mod000066400000000000000000000003351470316534700154100ustar00rootroot00000000000000module go.bug.st/f go 1.22.3 require github.com/stretchr/testify v1.9.0 require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) go-algorithms-0.4.0/go.sum000066400000000000000000000015611470316534700154370ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= go-algorithms-0.4.0/ptr.go000066400000000000000000000004251470316534700154360ustar00rootroot00000000000000package f // Ptr returns a pointer to v. func Ptr[T any](v T) *T { return &v } // UnwrapOrDefault returns the ptr value if it is not nil, otherwise returns the zero value. func UnwrapOrDefault[T any](ptr *T) T { if ptr != nil { return *ptr } var zero T return zero } go-algorithms-0.4.0/ptr_test.go000066400000000000000000000010231470316534700164700ustar00rootroot00000000000000package f_test import ( "testing" "github.com/stretchr/testify/assert" f "go.bug.st/f" ) func TestPtr(t *testing.T) { t.Run("int", func(t *testing.T) { assert.Equal(t, 12, *f.Ptr(12)) }) t.Run("string", func(t *testing.T) { assert.Equal(t, "hello", *f.Ptr("hello")) }) } func TestUnwrapOrDefault(t *testing.T) { t.Run("not nil", func(t *testing.T) { given := 12 assert.Equal(t, 12, f.UnwrapOrDefault(&given)) }) t.Run("nil", func(t *testing.T) { assert.Equal(t, "", f.UnwrapOrDefault[string](nil)) }) } go-algorithms-0.4.0/slices.go000066400000000000000000000056061470316534700161210ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f import ( "runtime" "sync" "sync/atomic" ) // Filter takes a slice of type []T and a Matcher[T]. It returns a newly // allocated slice containing only those elements of the input slice that // satisfy the matcher. func Filter[T any](values []T, matcher Matcher[T]) []T { var res []T for _, x := range values { if matcher(x) { res = append(res, x) } } return res } // Map applies the Mapper function to each element of the slice and returns // a new slice with the results in the same order. func Map[T, U any](values []T, mapper Mapper[T, U]) []U { res := make([]U, len(values)) for i, x := range values { res[i] = mapper(x) } return res } // ParallelMap applies the Mapper function to each element of the slice and returns // a new slice with the results in the same order. This is executed among multilple // goroutines in parallel. If jobs is specified it will indicate the maximum number // of goroutines to be spawned. func ParallelMap[T, U any](values []T, mapper Mapper[T, U], jobs ...int) []U { res := make([]U, len(values)) var j int if len(jobs) == 0 { j = runtime.NumCPU() } else if len(jobs) == 1 { j = jobs[0] } else { panic("jobs must be a single value") } j = min(j, len(values)) var idx atomic.Int64 idx.Store(-1) var wg sync.WaitGroup wg.Add(j) for count := 0; count < j; count++ { go func() { i := int(idx.Add(1)) for i < len(values) { res[i] = mapper(values[i]) i = int(idx.Add(1)) } wg.Done() }() } wg.Wait() return res } // Reduce applies the Reducer function to all elements of the input values // and returns the result. func Reduce[T any](values []T, reducer Reducer[T], initialValue ...T) T { var result T if len(initialValue) > 1 { panic("initialValue must be a single value") } else if len(initialValue) == 1 { result = initialValue[0] } for _, v := range values { result = reducer(result, v) } return result } // Equals return a Matcher that matches the given value func Equals[T comparable](value T) Matcher[T] { return func(x T) bool { return x == value } } // NotEquals return a Matcher that does not match the given value func NotEquals[T comparable](value T) Matcher[T] { return func(x T) bool { return x != value } } // Uniq return a copy of the input array with all duplicates removed func Uniq[T comparable](in []T) []T { have := map[T]bool{} var out []T for _, v := range in { if have[v] { continue } out = append(out, v) have[v] = true } return out } // Count returns the number of elements in the input array that match the given matcher func Count[T any](in []T, matcher Matcher[T]) int { var count int for _, v := range in { if matcher(v) { count++ } } return count } go-algorithms-0.4.0/slices_test.go000066400000000000000000000056141470316534700171570ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f_test import ( "strings" "testing" "github.com/stretchr/testify/require" f "go.bug.st/f" ) func TestFilter(t *testing.T) { a := []string{"aaa", "bbb", "ccc"} require.Equal(t, []string{"bbb", "ccc"}, f.Filter(a, func(x string) bool { return x > "b" })) b := []int{5, 9, 15, 2, 4, -2} require.Equal(t, []int{5, 9, 15}, f.Filter(b, func(x int) bool { return x > 4 })) } func TestEqualsAndNotEquals(t *testing.T) { require.True(t, f.Equals(int(0))(0)) require.False(t, f.Equals(int(1))(0)) require.True(t, f.Equals("")("")) require.False(t, f.Equals("abc")("")) require.False(t, f.NotEquals(int(0))(0)) require.True(t, f.NotEquals(int(1))(0)) require.False(t, f.NotEquals("")("")) require.True(t, f.NotEquals("abc")("")) } func TestMap(t *testing.T) { value := []string{"hello", " world ", " how are", "you? "} { parts := f.Map(value, strings.TrimSpace) require.Equal(t, 4, len(parts)) require.Equal(t, "hello", parts[0]) require.Equal(t, "world", parts[1]) require.Equal(t, "how are", parts[2]) require.Equal(t, "you?", parts[3]) } { parts := f.ParallelMap(value, strings.TrimSpace) require.Equal(t, 4, len(parts)) require.Equal(t, "hello", parts[0]) require.Equal(t, "world", parts[1]) require.Equal(t, "how are", parts[2]) require.Equal(t, "you?", parts[3]) } } func TestReduce(t *testing.T) { and := func(in ...bool) bool { return f.Reduce(in, func(a, b bool) bool { return a && b }, true) } require.True(t, and()) require.True(t, and(true)) require.False(t, and(false)) require.True(t, and(true, true)) require.False(t, and(true, false)) require.False(t, and(false, true)) require.False(t, and(false, false)) require.False(t, and(true, true, false)) require.False(t, and(false, true, false)) require.False(t, and(false, true, true)) require.True(t, and(true, true, true)) or := func(in ...bool) bool { return f.Reduce(in, func(a, b bool) bool { return a || b }, false) } require.False(t, or()) require.True(t, or(true)) require.False(t, or(false)) require.True(t, or(true, true)) require.True(t, or(true, false)) require.True(t, or(false, true)) require.False(t, or(false, false)) require.True(t, or(true, true, false)) require.True(t, or(false, true, false)) require.False(t, or(false, false, false)) require.True(t, or(true, true, true)) add := func(in ...int) int { return f.Reduce(in, func(a, b int) int { return a + b }) } require.Equal(t, 0, add()) require.Equal(t, 10, add(10)) require.Equal(t, 15, add(10, 2, 3)) } func TestCount(t *testing.T) { a := []string{"aaa", "bbb", "ccc"} require.Equal(t, 1, f.Count(a, f.Equals("bbb"))) require.Equal(t, 0, f.Count(a, f.Equals("ddd"))) require.Equal(t, 3, f.Count(a, f.NotEquals("ddd"))) } go-algorithms-0.4.0/types.go000066400000000000000000000011011470316534700157650ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f // Matcher is a function that tests if a given value matches a certain criteria. type Matcher[T any] func(T) bool // Reducer is a function that combines two values of the same type and return // the combined value. type Reducer[T any] func(T, T) T // Mapper is a function that converts a value of one type to another type. type Mapper[T, U any] func(T) U