This repository was archived by the owner on Feb 2, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
101 lines (91 loc) · 2.26 KB
/
utils.go
File metadata and controls
101 lines (91 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package functools
import "github.com/se-dev-pion/functools/types"
// Decorate wraps something with a function, mainly used for enhancing a function with another function.
func Decorate[T any](wrapper types.FuncT2T[T], f T) T {
return wrapper(f)
}
// Pack creates a slice for input elements.
func Pack[T any](params ...T) []T {
return params
}
// Lazy creates a function with no params that returns the result of input function called with input params.
func Lazy[T, R any](f types.FuncT2R[T, R], param T) types.FuncNone2T[R] {
return func() R {
return f(param)
}
}
// Partial creates a function that fixes input params with the input function.
func Partial[T, R any](f types.FuncTs2R[T, R], params ...T) types.FuncTs2R[T, R] {
return func(others ...T) R {
return f(append(params, others...)...)
}
}
// Flow creates a function connecting the handling process of input functions.
func Flow[T any](f ...types.FuncT2T[T]) types.FuncT2T[T] {
return func(param T) T {
output := param
for _, fn := range f {
output = fn(output)
}
return output
}
}
// Batch creates a function merging the handling process of input functions.
func Batch[T any](f ...types.FuncT2T[T]) types.FuncT2Ts[T] {
return func(param T) []T {
output := make([]T, len(f))
for i, fn := range f {
output[i] = fn(param)
}
return output
}
}
// Cached creates a function with cache that works in the same way as the input function.
func Cached[T comparable, R any](f types.FuncT2R[T, R]) types.FuncT2R[T, R] {
cache := make(map[T]R)
return func(param T) R {
if v, ok := cache[param]; ok {
return v
}
cache[param] = f(param)
return cache[param]
}
}
func extractChanElements[T any](ch chan T) []T {
output := make([]T, len(ch))
defer func() {
for _, item := range output {
ch <- item
}
}()
i := 0
for {
select {
case item, ok := <-ch:
if !ok {
goto END
}
output[i] = item
i++
default:
goto END
}
}
END:
return output
}
// Copy creates a shallow copy of slice/chan
func Copy[T any, E types.Sequence[T]](entry E) (copy E) {
v := any(entry)
switch e := v.(type) {
case []T:
copy = any(Pack(e...)).(E)
case chan T:
output := make(chan T, cap(e))
for _, item := range extractChanElements(e) {
output <- item
}
copy = any(output).(E)
}
return
}