Added math abs command. (#2789)

This commit is contained in:
xolve 2020-12-15 22:07:12 +05:30 committed by GitHub
parent 83c874666a
commit f377a3a7b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 90 additions and 4 deletions

View File

@ -217,6 +217,7 @@ pub fn create_default_context(interactive: bool) -> Result<EvaluationContext, Bo
whole_stream_command(AutoenvTrust), whole_stream_command(AutoenvTrust),
whole_stream_command(AutoenvUnTrust), whole_stream_command(AutoenvUnTrust),
whole_stream_command(Math), whole_stream_command(Math),
whole_stream_command(MathAbs),
whole_stream_command(MathAverage), whole_stream_command(MathAverage),
whole_stream_command(MathEval), whole_stream_command(MathEval),
whole_stream_command(MathMedian), whole_stream_command(MathMedian),

View File

@ -212,8 +212,8 @@ pub(crate) use last::Last;
pub(crate) use lines::Lines; pub(crate) use lines::Lines;
pub(crate) use ls::Ls; pub(crate) use ls::Ls;
pub(crate) use math::{ pub(crate) use math::{
Math, MathAverage, MathCeil, MathEval, MathFloor, MathMaximum, MathMedian, MathMinimum, Math, MathAbs, MathAverage, MathCeil, MathEval, MathFloor, MathMaximum, MathMedian,
MathMode, MathProduct, MathRound, MathStddev, MathSummation, MathVariance, MathMinimum, MathMode, MathProduct, MathRound, MathStddev, MathSummation, MathVariance,
}; };
pub(crate) use merge::Merge; pub(crate) use merge::Merge;
pub(crate) use mkdir::Mkdir; pub(crate) use mkdir::Mkdir;

View File

@ -0,0 +1,73 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{Primitive, Signature, UntaggedValue, Value};
pub struct SubCommand;
#[async_trait]
impl WholeStreamCommand 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"
}
async fn run(
&self,
args: CommandArgs,
_: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
let mapped = args.input.map(move |val| match val.value {
UntaggedValue::Primitive(Primitive::Int(val)) => {
UntaggedValue::int(val.magnitude().clone()).into()
}
UntaggedValue::Primitive(Primitive::Decimal(val)) => {
UntaggedValue::decimal(val.abs()).into()
}
UntaggedValue::Primitive(Primitive::Duration(val)) => {
UntaggedValue::duration(val.magnitude().clone()).into()
}
other => abs_default(other),
});
Ok(OutputStream::from_input(mapped))
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Get absolute of each value in a list of numbers",
example: "echo [-50 -100.0 25] | math abs",
result: Some(vec![
UntaggedValue::int(50).into(),
UntaggedValue::decimal_from_float(100.0, Span::default()).into(),
UntaggedValue::int(25).into(),
]),
}]
}
}
fn abs_default(_: UntaggedValue) -> Value {
UntaggedValue::Error(ShellError::unexpected(
"Only numerical values are supported",
))
.into()
}
#[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;
Ok(test_examples(SubCommand {})?)
}
}

View File

@ -1,3 +1,4 @@
pub mod abs;
pub mod avg; pub mod avg;
pub mod ceil; pub mod ceil;
pub mod command; pub mod command;
@ -16,6 +17,7 @@ pub mod variance;
mod reducers; mod reducers;
mod utils; mod utils;
pub use abs::SubCommand as MathAbs;
pub use avg::SubCommand as MathAverage; pub use avg::SubCommand as MathAverage;
pub use ceil::SubCommand as MathCeil; pub use ceil::SubCommand as MathCeil;
pub use command::Command as Math; pub use command::Command as Math;

View File

@ -242,8 +242,8 @@ impl UntaggedValue {
} }
/// Helper for creating date duration values /// Helper for creating date duration values
pub fn duration(nanos: BigInt) -> UntaggedValue { pub fn duration(nanos: impl Into<BigInt>) -> UntaggedValue {
UntaggedValue::Primitive(Primitive::Duration(nanos)) UntaggedValue::Primitive(Primitive::Duration(nanos.into()))
} }
/// Helper for creating datatime values /// Helper for creating datatime values

View File

@ -3,6 +3,7 @@
Mathematical functions that generally only operate on a list of numbers (integers, decimals, bytes) and tables. Mathematical functions that generally only operate on a list of numbers (integers, decimals, bytes) and tables.
Currently the following functions are implemented: Currently the following functions are implemented:
* `math abs`: Returns absolute values of a list of numbers
* `math avg`: Finds the average of a list of numbers or tables * `math avg`: Finds the average of a list of numbers or tables
* `math ceil`: Applies the ceil function to a list of numbers * `math ceil`: Applies the ceil function to a list of numbers
* [`math eval`](math-eval.md): Evaluates a list of math expressions into numbers * [`math eval`](math-eval.md): Evaluates a list of math expressions into numbers
@ -147,6 +148,15 @@ To get the average of the file sizes in a directory, simply pipe the size column
───┴──── ───┴────
``` ```
```shell
> echo [1 -2 -3.0] | math abs
───┬────────
0 │ 1
1 │ 2
2 │ 3.0000
───┴────────
```
### Dates ### Dates
```shell ```shell