layoutcss_parser/
harmonic.rs

1pub fn get_harmonic(value: &str, harmonic: f64) -> String {
2    // if its a css variable
3    if value.starts_with("--") {
4        return format!("var({})", value);
5    }
6
7    if value == "none" {
8        return "0.0".to_string();
9    }
10
11    if let Ok(x) = value.parse::<f64>() {
12        let value =  harmonic.powf(x).to_string();
13        return format!("{value:.5}rem").to_string();
14    };
15
16    // if the value is not a unit less number
17    // so not a harmonic number
18    // we return it as it is
19    value.to_string()
20}
21
22#[cfg(test)]
23mod tests {
24    use super::*; // Bring the function into scope for the tests
25
26    // Use 1.618 as the harmonic value for all tests
27    const HARMONIC: f64 = 1.618;
28
29    #[test]
30    fn test_numeric_values() {
31        // Test harmonic calculation for numeric values with harmonic = 1.618
32        assert_eq!(get_harmonic("2", HARMONIC), "2.617rem"); // 1.618^2
33        assert_eq!(get_harmonic("2.5", HARMONIC), "3.330rem"); // 1.618^2.5
34    }
35
36    #[test]
37    fn test_none_value() {
38        // Test for the "none" value, which should return "0.0"
39        assert_eq!(get_harmonic("none", HARMONIC), "0.0");
40    }
41
42    #[test]
43    fn test_css_variable() {
44        // Test for CSS variable values, they should be returned wrapped in var()
45        assert_eq!(get_harmonic("--main-color", HARMONIC), "var(--main-color)");
46        assert_eq!(get_harmonic("--font-size", HARMONIC), "var(--font-size)");
47    }
48
49    #[test]
50    fn test_non_numeric_values() {
51        // Test for non-numeric values (with units or other characters)
52        assert_eq!(get_harmonic("16px", HARMONIC), "16px");
53        assert_eq!(get_harmonic("1rem", HARMONIC), "1rem");
54        assert_eq!(get_harmonic("invalid", HARMONIC), "invalid");
55    }
56
57    #[test]
58    fn test_empty_string() {
59        // Test for empty string, should return an empty string as is
60        assert_eq!(get_harmonic("", HARMONIC), "");
61    }
62}
63