choiceValueParser<T> function

ValueParser<T> choiceValueParser<T>(
  1. List<T> choices,
  2. ValueParser<T> unconstrainedParser, {
  3. ValuePrinter<T>? printer,
})

Returns a ValueParser that constraints an already-parsed value to some sequence of acceptable inputs. See ValueParserExtensions.choice for a slightly more elegant alternative.

var twoOrFourParser = choiceValueParser([2, 4], intValueParser);
print(twoOrFourParser('2'));  // 2
twoOrFourParser('3');         // throws an exception

Implementation

ValueParser<T> choiceValueParser<T>(
        List<T> choices, ValueParser<T> unconstrainedParser,
        {ValuePrinter<T>? printer}) =>
    unconstrainedParser.also((value) {
      if (!choices.contains(value)) {
        var formattedChoices =
            choices.map(printer ?? toStringValuePrinter).join(', ');
        throw ValueParserException(
            'Value not in available choices: $formattedChoices');
      }
    });