add support for Floats for sort-by (#857)

This commit is contained in:
Michael Angerman 2022-01-26 14:44:37 -08:00 committed by GitHub
parent e8b8836977
commit a4421434d9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -7,6 +7,7 @@ use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span,
SyntaxShape, Value,
};
use std::cmp::Ordering;
#[derive(Clone)]
pub struct SortBy;
@ -155,7 +156,7 @@ pub fn process(
#[derive(Debug)]
pub enum CompareValues {
Ints(i64, i64),
// Floats(f64, f64),
Floats(f64, f64),
String(String, String),
Booleans(bool, bool),
Filesize(i64, i64),
@ -166,8 +167,7 @@ impl CompareValues {
pub fn compare(&self) -> std::cmp::Ordering {
match self {
CompareValues::Ints(left, right) => left.cmp(right),
// f64: std::cmp::Ord is required
// CompareValues::Floats(left, right) => left.cmp(right),
CompareValues::Floats(left, right) => process_floats(left, right),
CompareValues::String(left, right) => left.cmp(right),
CompareValues::Booleans(left, right) => left.cmp(right),
CompareValues::Filesize(left, right) => left.cmp(right),
@ -176,22 +176,29 @@ impl CompareValues {
}
}
pub fn process_floats(left: &f64, right: &f64) -> std::cmp::Ordering {
let result = left.partial_cmp(right);
match result {
Some(Ordering::Greater) => Ordering::Greater,
Some(Ordering::Less) => Ordering::Less,
_ => Ordering::Equal,
}
}
pub fn coerce_compare(
left: &Value,
right: &Value,
) -> Result<CompareValues, (&'static str, &'static str)> {
match (left, right) {
// (Value::Float { val: left, .. }, Value::Float { val: right, .. }) => {
// Ok(CompareValues::Floats(*left, *right))
// }
(Value::Float { val: left, .. }, Value::Float { val: right, .. }) => {
Ok(CompareValues::Floats(*left, *right))
}
(Value::Filesize { val: left, .. }, Value::Filesize { val: right, .. }) => {
Ok(CompareValues::Filesize(*left, *right))
}
(Value::Date { val: left, .. }, Value::Date { val: right, .. }) => {
Ok(CompareValues::Date(*left, *right))
}
(Value::Int { val: left, .. }, Value::Int { val: right, .. }) => {
Ok(CompareValues::Ints(*left, *right))
}