nu_command/math/
median.rs

1use crate::math::{avg::average, utils::run_with_function};
2use nu_engine::command_prelude::*;
3use std::cmp::Ordering;
4
5#[derive(Clone)]
6pub struct MathMedian;
7
8impl Command for MathMedian {
9    fn name(&self) -> &str {
10        "math median"
11    }
12
13    fn signature(&self) -> Signature {
14        Signature::build("math median")
15            .input_output_types(vec![
16                (Type::List(Box::new(Type::Number)), Type::Number),
17                (Type::List(Box::new(Type::Duration)), Type::Duration),
18                (Type::List(Box::new(Type::Filesize)), Type::Filesize),
19                (Type::Range, Type::Number),
20                (Type::table(), Type::record()),
21                (Type::record(), Type::record()),
22            ])
23            .allow_variants_without_examples(true)
24            .category(Category::Math)
25    }
26
27    fn description(&self) -> &str {
28        "Computes the median of a list of numbers."
29    }
30
31    fn search_terms(&self) -> Vec<&str> {
32        vec!["middle", "statistics"]
33    }
34
35    fn is_const(&self) -> bool {
36        true
37    }
38
39    fn run(
40        &self,
41        _engine_state: &EngineState,
42        _stack: &mut Stack,
43        call: &Call,
44        input: PipelineData,
45    ) -> Result<PipelineData, ShellError> {
46        run_with_function(call, input, median)
47    }
48
49    fn run_const(
50        &self,
51        _working_set: &StateWorkingSet,
52        call: &Call,
53        input: PipelineData,
54    ) -> Result<PipelineData, ShellError> {
55        run_with_function(call, input, median)
56    }
57
58    fn examples(&self) -> Vec<Example> {
59        vec![
60            Example {
61                description: "Compute the median of a list of numbers",
62                example: "[3 8 9 12 12 15] | math median",
63                result: Some(Value::test_float(10.5)),
64            },
65            Example {
66                description: "Compute the medians of the columns of a table",
67                example: "[{a: 1 b: 3} {a: 2 b: -1} {a: -3 b: 5}] | math median",
68                result: Some(Value::test_record(record! {
69                    "a" => Value::test_int(1),
70                    "b" => Value::test_int(3),
71                })),
72            },
73            Example {
74                description: "Find the median of a list of file sizes",
75                example: "[5KB 10MB 200B] | math median",
76                result: Some(Value::test_filesize(5 * 1_000)),
77            },
78        ]
79    }
80}
81
82enum Pick {
83    MedianAverage,
84    Median,
85}
86
87pub fn median(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
88    let take = if values.len() % 2 == 0 {
89        Pick::MedianAverage
90    } else {
91        Pick::Median
92    };
93
94    let mut sorted = values
95        .iter()
96        .filter(|x| !x.as_float().is_ok_and(f64::is_nan))
97        .collect::<Vec<_>>();
98
99    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
100
101    match take {
102        Pick::Median => {
103            let idx = (values.len() as f64 / 2.0).floor() as usize;
104            Ok(sorted
105                .get(idx)
106                .ok_or_else(|| ShellError::UnsupportedInput {
107                    msg: "Empty input".to_string(),
108                    input: "value originates from here".into(),
109                    msg_span: head,
110                    input_span: span,
111                })?
112                .to_owned()
113                .to_owned())
114        }
115        Pick::MedianAverage => {
116            let idx_end = values.len() / 2;
117            let idx_start = idx_end - 1;
118
119            let left = sorted
120                .get(idx_start)
121                .ok_or_else(|| ShellError::UnsupportedInput {
122                    msg: "Empty input".to_string(),
123                    input: "value originates from here".into(),
124                    msg_span: head,
125                    input_span: span,
126                })?
127                .to_owned()
128                .to_owned();
129
130            let right = sorted
131                .get(idx_end)
132                .ok_or_else(|| ShellError::UnsupportedInput {
133                    msg: "Empty input".to_string(),
134                    input: "value originates from here".into(),
135                    msg_span: head,
136                    input_span: span,
137                })?
138                .to_owned()
139                .to_owned();
140
141            average(&[left, right], span, head)
142        }
143    }
144}
145
146#[cfg(test)]
147mod test {
148    use super::*;
149
150    #[test]
151    fn test_examples() {
152        use crate::test_examples;
153
154        test_examples(MathMedian {})
155    }
156}