-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit f5d818e
Showing
9 changed files
with
326 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
|
||
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. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
// | ||
// 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 | ||
|
||
// 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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// | ||
// 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] interface { | ||
Send(T) | ||
Await() T | ||
} | ||
|
||
type future[T any] struct { | ||
wg sync.WaitGroup | ||
value T | ||
} | ||
|
||
// NewFuture creates a new Future[T] | ||
func NewFuture[T any]() Future[T] { | ||
res := &future[T]{} | ||
res.wg.Add(1) | ||
return res | ||
} | ||
|
||
// Send a result in the Future. Threads waiting for result will be unlocked. | ||
func (f *future[T]) Send(value T) { | ||
f.value = value | ||
f.wg.Done() | ||
} | ||
|
||
// Await for a result from the Future, blocks until a result is available. | ||
func (f *future[T]) Await() T { | ||
f.wg.Wait() | ||
return f.value | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
// | ||
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
module 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 | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
github.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= |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
// | ||
// 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") | ||
} | ||
N := min(j, len(values)) | ||
|
||
var idx atomic.Int64 | ||
idx.Store(-1) | ||
var wg sync.WaitGroup | ||
wg.Add(N) | ||
for count := 0; count < N; 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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// | ||
// 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]) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
// | ||
// 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 |