nushell/crates/nu-command/src/commands/math/round.rs

107 lines
3.1 KiB
Rust
Raw Normal View History

use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
2020-10-29 04:14:08 +01:00
use nu_protocol::{Primitive, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged;
pub struct SubCommand;
2020-10-29 04:14:08 +01:00
#[derive(Deserialize)]
struct Arguments {
precision: Option<Tagged<i64>>,
}
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"math round"
}
fn signature(&self) -> Signature {
2020-10-29 04:14:08 +01:00
Signature::build("math round").named(
"precision",
SyntaxShape::Number,
"digits of precision",
Some('p'),
)
}
fn usage(&self) -> &str {
"Applies the round function to a list of numbers"
}
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
operate(args)
}
fn examples(&self) -> Vec<Example> {
2020-10-29 04:14:08 +01:00
vec![
Example {
description: "Apply the round function to a list of numbers",
example: "echo [1.5 2.3 -3.1] | math round",
result: Some(vec![
UntaggedValue::int(2).into(),
UntaggedValue::int(2).into(),
UntaggedValue::int(-3).into(),
]),
},
Example {
description: "Apply the round function with precision specified",
example: "echo [1.555 2.333 -3.111] | math round -p 2",
result: Some(vec![
UntaggedValue::decimal_from_float(1.56, Span::default()).into(),
UntaggedValue::decimal_from_float(2.33, Span::default()).into(),
UntaggedValue::decimal_from_float(-3.11, Span::default()).into(),
]),
},
]
}
}
fn operate(args: CommandArgs) -> Result<ActionStream, ShellError> {
let (Arguments { precision }, input) = args.process()?;
2020-10-29 04:14:08 +01:00
let precision = precision.map(|p| p.item).unwrap_or(0);
let mapped = input.map(move |val| match val.value {
UntaggedValue::Primitive(Primitive::Int(val)) => round_big_int(val),
UntaggedValue::Primitive(Primitive::Decimal(val)) => round_big_decimal(val, precision),
other => round_default(other),
});
Ok(ActionStream::from_input(mapped))
2020-10-29 04:14:08 +01:00
}
fn round_big_int(val: BigInt) -> Value {
UntaggedValue::int(val).into()
}
2020-10-29 04:14:08 +01:00
fn round_big_decimal(val: BigDecimal, precision: i64) -> Value {
if precision > 0 {
UntaggedValue::decimal(val.with_scale(precision + 1).round(precision)).into()
2020-10-29 04:14:08 +01:00
} else {
let (rounded, _) = val
.with_scale(precision + 1)
.round(precision)
.as_bigint_and_exponent();
2020-10-29 04:14:08 +01:00
UntaggedValue::int(rounded).into()
}
}
fn round_default(_: UntaggedValue) -> Value {
UntaggedValue::Error(ShellError::unexpected(
"Only numerical values are supported",
))
.into()
}
2020-10-29 04:14:08 +01:00
#[cfg(test)]
mod tests {
use super::ShellError;
use super::SubCommand;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
2021-02-12 11:13:14 +01:00
test_examples(SubCommand {})
}
}