-
Notifications
You must be signed in to change notification settings - Fork 3
/
list.gleam
90 lines (77 loc) · 1.91 KB
/
list.gleam
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
import valid/common.{type Validator}
import gleam/function
import gleam/list
import gleam/option.{type Option, None, Some}
fn is_not_empty_check(value: List(a)) -> Option(List(a)) {
case list.is_empty(value) {
True -> None
False -> Some(value)
}
}
/// Validate that a list is not empty
pub fn is_not_empty(error: error) {
common.custom(error, is_not_empty_check)
}
fn min_length_check(min: Int) {
fn(value: List(a)) -> Option(List(a)) {
case list.length(value) < min {
True -> None
False -> Some(value)
}
}
}
/// Validate the min number of items in a list
pub fn min_length(error: error, min: Int) {
common.custom(error, min_length_check(min))
}
fn max_length_check(max: Int) {
fn(value: List(a)) -> Option(List(a)) {
case list.length(value) > max {
True -> None
False -> Some(value)
}
}
}
/// Validate the max number of items in a list
pub fn max_length(error: error, max: Int) {
common.custom(error, max_length_check(max))
}
/// Validate a list of items.
///
/// Run the given validator for each item returning all the errors.
///
/// ## Example
///
/// type Collection = { Collection(items: List(String) ) }
///
/// let list_validator = v_list.every(
/// v_string.min_length("Must be at least 3", 3)
/// )
///
/// let validator = fn(collection: Collection) {
/// v.build1(Collection)
/// |> v.validate(collection.items, list_validator)
/// }
pub fn every(validator: Validator(input, output, error)) {
fn(items: List(input)) {
let results =
items
|> list.map(validator)
let errors =
results
|> list.map(fn(result) {
case result {
Ok(_) -> []
Error(#(_first, rest)) -> rest
}
})
|> list.flatten
let ok_items =
results
|> list.filter_map(function.identity)
case list.first(errors) {
Error(Nil) -> Ok(ok_items)
Ok(head) -> Error(#(head, errors))
}
}
}