Skip to content

Commit

Permalink
docs for constraint helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
TanklesXL committed May 6, 2024
1 parent 85b629b commit 4203f8c
Showing 1 changed file with 41 additions and 10 deletions.
51 changes: 41 additions & 10 deletions src/glint/constraint.gleam
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import gleam/list
import gleam/result
import gleam/set
import gleam/string
import snag
Expand All @@ -9,7 +8,15 @@ import snag
pub type Constraint(a) =
fn(a) -> snag.Result(a)

/// returns a Constraint that ensures the parsed flag value is one of the allowed values.
/// Returns a Constraint that ensures the parsed flag value is one of the allowed values.
///
/// ```gleam
/// import glint
/// import glint/constraint
/// ...
/// glint.int_flag("my_flag")
/// |> glint.constraint(constraint.one_of([1, 2, 3, 4]))
/// ```
///
pub fn one_of(allowed: List(a)) -> Constraint(a) {
let allowed_set = set.from_list(allowed)
Expand All @@ -32,7 +39,15 @@ pub fn one_of(allowed: List(a)) -> Constraint(a) {
}
}

/// returns a Constraint that ensures the parsed flag value is not one of the disallowed values.
/// Returns a Constraint that ensures the parsed flag value is not one of the disallowed values.
///
/// ```gleam
/// import glint
/// import glint/constraint
/// ...
/// glint.int_flag("my_flag")
/// |> glint.constraint(constraint.none_of([1, 2, 3, 4]))
/// ```
///
pub fn none_of(disallowed: List(a)) -> Constraint(a) {
let disallowed_set = set.from_list(disallowed)
Expand All @@ -57,17 +72,33 @@ pub fn none_of(disallowed: List(a)) -> Constraint(a) {
}
}

/// each is a convenience function for applying a Constraint(a) to a List(a).
/// This is a convenience function for applying a Constraint(a) to a List(a).
/// This is useful because the default behaviour for constraints on lists is that they will apply to the list as a whole.
///
/// For example, to apply one_of to all items in a `List(Int)`:
///
/// Via `use`:
/// ```gleam
/// import glint
/// import glint/constraint
/// ...
/// use li <- glint.flag_constraint(glint.int_flag("my_flag"))
/// use i <- constraint.each()
/// i |> one_of([1, 2, 3, 4])
/// ```
///
/// via a pipe:
/// ```gleam
/// [1, 2, 3, 4] |> one_of |> each
/// import glint
/// import glint/constraint
/// ...
/// glint.int_flag("my_flag")
/// |> glint.flag_constraint(
/// constraint.one_of([1,2,3,4])
/// |> constraint.each
/// )
/// ```
///
pub fn each(constraint: Constraint(a)) -> Constraint(List(a)) {
fn(l: List(a)) -> snag.Result(List(a)) {
l
|> list.try_map(constraint)
|> result.replace(l)
}
list.try_map(_, constraint)
}

0 comments on commit 4203f8c

Please sign in to comment.