2021-10-21 16:52:26 +02:00
|
|
|
use nu_protocol::ast::Call;
|
|
|
|
use nu_protocol::engine::{Command, EvaluationContext};
|
2021-10-25 01:58:18 +02:00
|
|
|
use nu_protocol::{Example, ShellError, Signature, Span, Value};
|
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,
|
|
|
|
_context: &EvaluationContext,
|
|
|
|
call: &Call,
|
|
|
|
input: Value,
|
|
|
|
) -> Result<Value, ShellError> {
|
2021-10-21 17:29:57 +02:00
|
|
|
let head = call.head;
|
2021-10-25 01:58:18 +02:00
|
|
|
match input {
|
|
|
|
Value::List { vals, span } => Ok(Value::List {
|
|
|
|
vals: vals
|
|
|
|
.into_iter()
|
|
|
|
.map(move |val| abs_helper(val, head))
|
|
|
|
.collect(),
|
|
|
|
span,
|
|
|
|
}),
|
|
|
|
other => match abs_helper(other, head) {
|
|
|
|
Value::Error { error } => Err(error),
|
|
|
|
ok => Ok(ok),
|
|
|
|
},
|
|
|
|
}
|
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 {})
|
|
|
|
}
|
|
|
|
}
|