Skip to content

Tiny snippet for conditional coloring #199

Description

@jpswensen

This may seem like something small, but I have found it very useful for doing conditional coloring of some strings.
Here is an example of how I have used it

let hh_decr_condition = hhm3 < 0.0 && hhm2 < hhm3 && hhm1 < hhm2;
let hh_decr_string = format!("{:+.6}<{:+.6}<{:+.6}<0.0", hhm1, hhm2, hhm3).color_if(hh_decr_condition, Color::Green, Color::Red);



/// An extension trait to add a `color_if` method.
trait ConditionalColorize {
    /// Colors the text with `true_color` if `cond` is true,
    /// otherwise colors it with `false_color`.
    fn color_if(self, cond: bool, true_color: Color, false_color: Color) -> ColoredString;
}

impl<'a> ConditionalColorize for &'a str {
    fn color_if(self, cond: bool, true_color: Color, false_color: Color) -> ColoredString {
        if cond {
            self.color(true_color)
        } else {
            self.color(false_color)
        }
    }
}

impl ConditionalColorize for ColoredString {
    fn color_if(self, cond: bool, true_color: Color, false_color: Color) -> ColoredString {
        if cond {
            self.color(true_color)
        } else {
            self.color(false_color)
        }
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions