2021-11-01 21:29:34 +00:00
|
|
|
use crate::math::reducers::{reducer_for, Reduce};
|
|
|
|
use crate::math::utils::run_with_function;
|
|
|
|
use nu_protocol::ast::Call;
|
|
|
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
2022-11-09 21:55:05 +00:00
|
|
|
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
|
2021-11-01 21:29:34 +00:00
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct SubCommand;
|
|
|
|
|
|
|
|
impl Command for SubCommand {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"math sum"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
2022-11-09 21:55:05 +00:00
|
|
|
Signature::build("math sum")
|
2023-07-14 03:20:35 +00:00
|
|
|
.input_output_types(vec![
|
|
|
|
(Type::List(Box::new(Type::Number)), Type::Number),
|
2023-07-28 21:34:47 +00:00
|
|
|
(Type::List(Box::new(Type::Duration)), Type::Duration),
|
|
|
|
(Type::List(Box::new(Type::Filesize)), Type::Filesize),
|
2023-07-14 03:20:35 +00:00
|
|
|
(Type::Range, Type::Number),
|
|
|
|
(Type::Table(vec![]), Type::Table(vec![])),
|
|
|
|
])
|
|
|
|
.allow_variants_without_examples(true)
|
2022-11-09 21:55:05 +00:00
|
|
|
.category(Category::Math)
|
2021-11-01 21:29:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
2023-03-01 05:33:02 +00:00
|
|
|
"Returns the sum of a list of numbers or of each column in a table."
|
2021-11-01 21:29:34 +00:00
|
|
|
}
|
|
|
|
|
2022-04-18 21:33:32 +00:00
|
|
|
fn search_terms(&self) -> Vec<&str> {
|
2022-11-09 21:55:05 +00:00
|
|
|
vec!["plus", "add", "total", "+"]
|
2022-04-18 21:33:32 +00:00
|
|
|
}
|
|
|
|
|
2021-11-01 21:29:34 +00:00
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
_engine_state: &EngineState,
|
|
|
|
_stack: &mut Stack,
|
|
|
|
call: &Call,
|
|
|
|
input: PipelineData,
|
2023-02-05 21:17:46 +00:00
|
|
|
) -> Result<PipelineData, ShellError> {
|
2021-11-01 21:29:34 +00:00
|
|
|
run_with_function(call, input, summation)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn examples(&self) -> Vec<Example> {
|
|
|
|
vec![
|
|
|
|
Example {
|
|
|
|
description: "Sum a list of numbers",
|
|
|
|
example: "[1 2 3] | math sum",
|
|
|
|
result: Some(Value::test_int(6)),
|
|
|
|
},
|
|
|
|
Example {
|
|
|
|
description: "Get the disk usage for the current directory",
|
|
|
|
example: "ls | get size | math sum",
|
|
|
|
result: None,
|
|
|
|
},
|
|
|
|
]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-31 19:47:46 +00:00
|
|
|
pub fn summation(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
|
2021-11-01 21:29:34 +00:00
|
|
|
let sum_func = reducer_for(Reduce::Summation);
|
2023-07-31 19:47:46 +00:00
|
|
|
sum_func(Value::nothing(head), values.to_vec(), span, head)
|
2021-11-01 21:29:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_examples() {
|
|
|
|
use crate::test_examples;
|
|
|
|
|
|
|
|
test_examples(SubCommand {})
|
|
|
|
}
|
|
|
|
}
|