nu_command/filters/
enumerate.rs

1use nu_engine::command_prelude::*;
2
3#[derive(Clone)]
4pub struct Enumerate;
5
6impl Command for Enumerate {
7    fn name(&self) -> &str {
8        "enumerate"
9    }
10
11    fn description(&self) -> &str {
12        "Enumerate the elements in a stream."
13    }
14
15    fn search_terms(&self) -> Vec<&str> {
16        vec!["itemize"]
17    }
18
19    fn signature(&self) -> nu_protocol::Signature {
20        Signature::build("enumerate")
21            .input_output_types(vec![(Type::Any, Type::table())])
22            .category(Category::Filters)
23    }
24
25    fn examples(&self) -> Vec<Example> {
26        vec![Example {
27            description: "Add an index to each element of a list",
28            example: r#"[a, b, c] | enumerate "#,
29            result: Some(Value::test_list(vec![
30                Value::test_record(record! {
31                    "index" =>  Value::test_int(0),
32                    "item" =>   Value::test_string("a"),
33                }),
34                Value::test_record(record! {
35                    "index" =>  Value::test_int(1),
36                    "item" =>   Value::test_string("b"),
37                }),
38                Value::test_record(record! {
39                    "index" =>  Value::test_int(2),
40                    "item" =>   Value::test_string("c"),
41                }),
42            ])),
43        }]
44    }
45
46    fn run(
47        &self,
48        engine_state: &EngineState,
49        _stack: &mut Stack,
50        call: &Call,
51        input: PipelineData,
52    ) -> Result<PipelineData, ShellError> {
53        let head = call.head;
54        let metadata = input.metadata();
55
56        Ok(input
57            .into_iter()
58            .enumerate()
59            .map(move |(idx, x)| {
60                Value::record(
61                    record! {
62                        "index" => Value::int(idx as i64, head),
63                        "item" => x,
64                    },
65                    head,
66                )
67            })
68            .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata))
69    }
70}
71
72#[cfg(test)]
73mod test {
74    use super::*;
75
76    #[test]
77    fn test_examples() {
78        use crate::test_examples;
79
80        test_examples(Enumerate {})
81    }
82}