nu_command/filters/
any.rs

1use super::utils;
2use nu_engine::command_prelude::*;
3
4#[derive(Clone)]
5pub struct Any;
6
7impl Command for Any {
8    fn name(&self) -> &str {
9        "any"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build(self.name())
14            .input_output_types(vec![(Type::List(Box::new(Type::Any)), Type::Bool)])
15            .required(
16                "predicate",
17                SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
18                "A closure that must evaluate to a boolean.",
19            )
20            .category(Category::Filters)
21    }
22
23    fn description(&self) -> &str {
24        "Tests if any element of the input fulfills a predicate expression."
25    }
26
27    fn search_terms(&self) -> Vec<&str> {
28        vec!["some", "or"]
29    }
30
31    fn examples(&self) -> Vec<Example<'_>> {
32        vec![
33            Example {
34                description: "Check if a list contains any true values",
35                example: "[false true true false] | any {}",
36                result: Some(Value::test_bool(true)),
37            },
38            Example {
39                description: "Check if any row's status is the string 'DOWN'",
40                example: "[[status]; [UP] [DOWN] [UP]] | any {|el| $el.status == DOWN }",
41                result: Some(Value::test_bool(true)),
42            },
43            Example {
44                description: "Check that any item is a string",
45                example: "[1 2 3 4] | any {|| ($in | describe) == 'string' }",
46                result: Some(Value::test_bool(false)),
47            },
48            Example {
49                description: "Check if any value is equal to twice its own index",
50                example: "[9 8 7 6] | enumerate | any {|i| $i.item == $i.index * 2 }",
51                result: Some(Value::test_bool(true)),
52            },
53            Example {
54                description: "Check if any of the values are odd, using a stored closure",
55                example: "let cond = {|e| $e mod 2 == 1 }; [2 4 1 6 8] | any $cond",
56                result: Some(Value::test_bool(true)),
57            },
58        ]
59    }
60
61    fn run(
62        &self,
63        engine_state: &EngineState,
64        stack: &mut Stack,
65        call: &Call,
66        input: PipelineData,
67    ) -> Result<PipelineData, ShellError> {
68        utils::boolean_fold(engine_state, stack, call, input, true)
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn test_examples() {
78        use crate::test_examples;
79
80        test_examples(Any)
81    }
82}