nushell/crates/nu-command/src/math/abs.rs

85 lines
2.1 KiB
Rust
Raw Normal View History

2021-10-21 16:52:26 +02:00
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Example, PipelineData, ShellError, Signature, Span, Value};
2021-10-21 16:52:26 +02:00
#[derive(Clone)]
2021-10-21 16:52:26 +02:00
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math abs"
}
fn signature(&self) -> Signature {
Signature::build("math abs")
}
fn usage(&self) -> &str {
"Returns absolute values of a list of numbers"
}
2021-10-25 01:58:18 +02:00
fn run(
&self,
2021-10-28 06:13:10 +02:00
engine_state: &EngineState,
_stack: &mut Stack,
2021-10-25 01:58:18 +02:00
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
2021-10-21 17:29:57 +02:00
let head = call.head;
2021-10-28 06:13:10 +02:00
input.map(
move |value| abs_helper(value, head),
engine_state.ctrlc.clone(),
)
2021-10-21 16:52:26 +02:00
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Get absolute of each value in a list of numbers",
2021-10-25 13:10:17 +02:00
example: "[-50 -100.0 25] | math abs",
2021-10-25 01:58:18 +02:00
result: Some(Value::List {
2021-10-21 17:29:57 +02:00
vals: vec![
Value::test_int(50),
2021-10-25 01:58:18 +02:00
Value::Float {
val: 100.0,
span: Span::unknown(),
},
2021-10-21 17:29:57 +02:00
Value::test_int(25),
],
span: Span::unknown(),
}),
2021-10-21 16:52:26 +02:00
}]
}
}
2021-10-25 01:58:18 +02:00
fn abs_helper(val: Value, head: Span) -> Value {
match val {
Value::Int { val, span } => Value::int(val.abs(), span),
Value::Float { val, span } => Value::Float {
val: val.abs(),
span,
},
Value::Duration { val, span } => Value::Duration {
val: val.abs(),
span,
},
_ => Value::Error {
error: ShellError::UnsupportedInput(
String::from("Only numerical values are supported"),
head,
),
},
}
2021-10-21 16:52:26 +02:00
}
#[cfg(test)]
2021-10-25 01:58:18 +02:00
mod test {
use super::*;
2021-10-21 16:52:26 +02:00
#[test]
2021-10-25 01:58:18 +02:00
fn test_examples() {
use crate::test_examples;
2021-10-21 16:52:26 +02:00
test_examples(SubCommand {})
}
}