Functional Weave
Code in Python

charts.palette@1.0.0

impl/rust.rs

1,291 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::charts_palette_data::PALETTES;  ← this capability’s own data, compiled from data/palettes.json into the same file by fune build

/// The first `count` colours of a named categorical scheme, in its order.
/// Asking for more colours than the scheme has is an error unless `cycle`
/// says repeating them is acceptable.
///
/// # Panics
/// Panics on an unknown scheme, a negative count, or too many colours
/// without `cycle`.
pub fn palette(scheme: &str, count: i64, cycle: bool) -> Vec<String> {
    let mut rows: Vec<_> = PALETTES.iter().filter(|c| c.scheme == scheme).collect();
    rows.sort_by_key(|c| c.position);
    let colours: Vec<String> = rows.iter().map(|c| c.hex.to_string()).collect();
    if colours.is_empty() {
        panic!("unknown palette \"{}\"; use okabe-ito or tol-bright", scheme);
    }
    if count < 0 {
        panic!("count must be a whole number of at least 0, received {}", count);
    }
    if count as usize > colours.len() && !cycle {
        panic!("palette \"{}\" has only {} colours; pass cycle to repeat them", scheme, colours.len());
    }
    (0..count as usize).map(|i| colours[i % colours.len()].clone()).collect()
}

pub fn fune_vector(args: &[Value]) -> Value {
    let out = palette(args[0].as_str(), args[1].as_i64(), args[2].as_bool());
    Value::Arr(out.iter().map(|s| Value::str(s)).collect())
}