-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter.go
More file actions
78 lines (74 loc) · 2.04 KB
/
filter.go
File metadata and controls
78 lines (74 loc) · 2.04 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
package result
// Filter checks a predicate on the Ok value.
// If the result is Ok and the predicate returns true, the result is returned unchanged.
// If the result is Ok and the predicate returns false, returns Err with the provided error.
// If the result is already Err, it is returned unchanged.
//
// This is useful for adding validation checks to a successful result.
//
// Example:
//
// result.Ok(email).
// Filter(func(e Email) bool {
// return !isBlacklisted(e)
// }, ErrEmailBlacklisted{})
func (r Result[T]) Filter(predicate func(T) bool, err error) Result[T] {
if r.IsErr() {
return r
}
if !predicate(r.value) {
return Result[T]{
err: err,
op: r.op,
meta: r.meta,
}
}
return r
}
// FilterNot is the inverse of Filter - fails if predicate returns true.
// This is useful when you want to check that something is NOT the case.
//
// Example:
//
// result.Ok(email).
// FilterNot(func(e Email) bool {
// return emailExists(e)
// }, ErrEmailAlreadyExists{})
func (r Result[T]) FilterNot(predicate func(T) bool, err error) Result[T] {
return r.Filter(func(v T) bool { return !predicate(v) }, err)
}
// When converts a boolean condition into a Result check.
// If condition is true, the result is returned unchanged.
// If condition is false, returns Err with the provided error.
// If the result is already Err, it is returned unchanged.
//
// This is useful when you have an external condition to check.
//
// Example:
//
// exists := repo.ExistsByEmail(ctx, email)
// result.Ok(email).
// When(!exists, ErrEmailAlreadyExists{})
func (r Result[T]) When(condition bool, err error) Result[T] {
if r.IsErr() {
return r
}
if !condition {
return Result[T]{
err: err,
op: r.op,
meta: r.meta,
}
}
return r
}
// Unless is the inverse of When - fails if condition is true.
//
// Example:
//
// exists := repo.ExistsByEmail(ctx, email)
// result.Ok(email).
// Unless(exists, ErrEmailAlreadyExists{})
func (r Result[T]) Unless(condition bool, err error) Result[T] {
return r.When(!condition, err)
}