Functional Weave
Code in Rust

charts.format@1.0.0

impl/rust/format_tick.rs

924 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::math_round_float::round_float;  ← from math.round-float ^1.0.0 · built alongside by fune
use super::text_format_decimal::format_decimal;  ← from text.format-decimal ^1.0.0 · built alongside by fune

/// The fewest decimal places (0 to 12) that write x exactly; 12 if none do.
pub fn places_for(x: f64) -> i64 {
    let a = x.abs();
    for d in 0..12 {
        if round_float(a, d) == a {
            return d;
        }
    }
    12
}

/// A tick label with as many decimal places as the step needs, comma-grouped.
///
/// # Panics
/// Panics if the step is not finite or the value is too large to format.
pub fn format_tick(value: f64, step: f64) -> String {
    if !step.is_finite() {
        panic!("step must be a finite number, received {}", step);
    }
    let places = if step == 0.0 { places_for(value) } else { places_for(step) };
    format_decimal(value, places, false, ",")
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::str(&format_tick(args[0].as_f64(), args[1].as_f64()))
}