Functional Weave
Code in Rust

charts.format@1.0.0

impl/rust/format_date.rs

941 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::dates_add_days::parse_iso_date;  ← from dates.add-days ^1.0.0 · built alongside by fune

const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

/// A date as a tick label for the interval it stands for.
///
/// # Panics
/// Panics on an invalid date or an unknown label.
pub fn format_date(iso: &str, label: &str) -> String {
    let date = parse_iso_date(iso);
    let year = &iso[0..4];
    let month = MONTHS[(date.month - 1) as usize];
    match label {
        "day" | "week" => format!("{} {}", date.day, month),
        "month" => format!("{} {}", month, year),
        "quarter" => format!("Q{} {}", (date.month - 1) / 3 + 1, year),
        "year" => year.to_string(),
        other => panic!("unknown date label \"{}\"; use day, week, month, quarter or year", other),
    }
}

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