nsh-js 0.8.1

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
Documentation
//! List formatting (`Intl.ListFormat`): a list joined with the language's
//! conjunction (`apples, oranges and pears`), disjunction (`tea or coffee`)
//! or unit separator (`10 m`), from CLDR's list patterns (`locale.rs`).
//! The output is a list of parts (`formatToParts`); `format` joins them.

use super::{
    Part,
    locale::{Joint, Lists},
};

/// What a list is joined with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Type {
    Conjunction,
    Disjunction,
    Unit,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Style {
    Long,
    Short,
    Narrow,
}

/// Resolved options.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Format {
    pub(crate) kind: Type,
    pub(crate) style: Style,
}

impl Format {
    fn patterns<'a>(&self, lists: &'a Lists) -> &'a Joint {
        let patterns = match self.kind {
            Type::Conjunction => &lists.conjunction,
            Type::Disjunction => &lists.disjunction,
            Type::Unit => &lists.unit,
        };
        match self.style {
            Style::Long => &patterns.long,
            Style::Short => &patterns.short,
            Style::Narrow => &patterns.narrow,
        }
    }
}

/// The separator of a pattern (`{0}` and `{1}` are the items).
fn separator(pattern: &str) -> &str {
    pattern
        .strip_prefix("{0}")
        .and_then(|p| p.strip_suffix("{1}"))
        .unwrap_or(pattern)
}

/// `items`, joined as `format` asks.
pub(crate) fn format(items: &[String], format: &Format, lists: &Lists) -> Vec<Part> {
    let patterns = format.patterns(lists);
    let element = |s: &str| Part {
        kind: "element",
        value: s.to_owned(),
    };
    let literal = |s: &str| Part {
        kind: "literal",
        value: s.to_owned(),
    };
    match items {
        [] => Vec::new(),
        [one] => vec![element(one)],
        [first, second] => vec![
            element(first),
            literal(separator(&patterns.pair)),
            element(second),
        ],
        [first, second, rest @ ..] => {
            let mut parts = vec![
                element(first),
                literal(separator(&patterns.start)),
                element(second),
            ];
            let last = rest.len() - 1;
            for item in &rest[..last] {
                parts.push(literal(separator(&patterns.middle)));
                parts.push(element(item));
            }
            parts.push(literal(separator(&patterns.end)));
            parts.push(element(&rest[last]));
            parts
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::web::format::locale;

    fn joint(list: &[&str], kind: Type, style: Style, lang: &str) -> String {
        let locale = locale::resolve(&[lang.to_owned()], "en-US");
        let items: Vec<String> = list.iter().map(|s| (*s).to_owned()).collect();
        let format = Format { kind, style };
        super::format(&items, &format, &locale.lists)
            .iter()
            .map(|p| p.value.as_str())
            .collect()
    }

    #[test]
    fn joins_lists_by_their_count() {
        assert_eq!(joint(&[], Type::Conjunction, Style::Long, "en"), "");
        assert_eq!(
            joint(&["apples"], Type::Conjunction, Style::Long, "en"),
            "apples"
        );
        assert_eq!(
            joint(&["apples", "oranges"], Type::Conjunction, Style::Long, "en"),
            "apples and oranges"
        );
        assert_eq!(
            joint(
                &["apples", "oranges", "pears"],
                Type::Conjunction,
                Style::Long,
                "en"
            ),
            "apples, oranges, and pears"
        );
        assert_eq!(
            joint(
                &["apples", "oranges", "pears", "plums"],
                Type::Conjunction,
                Style::Long,
                "en"
            ),
            "apples, oranges, pears, and plums"
        );
    }

    #[test]
    fn every_type_and_style_in_english() {
        let fruits = ["apples", "oranges", "pears"];
        let units = ["10", "m", "s"];
        for (kind, style, list, want) in [
            (
                Type::Conjunction,
                Style::Long,
                &fruits[..],
                "apples, oranges, and pears",
            ),
            (
                Type::Conjunction,
                Style::Short,
                &fruits[..],
                "apples, oranges, & pears",
            ),
            (
                Type::Conjunction,
                Style::Narrow,
                &fruits[..],
                "apples, oranges, pears",
            ),
            (
                Type::Disjunction,
                Style::Long,
                &fruits[..],
                "apples, oranges, or pears",
            ),
            (
                Type::Disjunction,
                Style::Short,
                &fruits[..],
                "apples, oranges, or pears",
            ),
            (
                Type::Disjunction,
                Style::Narrow,
                &fruits[..],
                "apples, oranges, or pears",
            ),
            (Type::Unit, Style::Long, &units[..], "10, m, s"),
            (Type::Unit, Style::Short, &units[..], "10, m, s"),
            (Type::Unit, Style::Narrow, &units[..], "10 m s"),
        ] {
            assert_eq!(joint(list, kind, style, "en"), want, "{kind:?} {style:?}");
        }
    }

    #[test]
    fn languages_join_as_they_say() {
        assert_eq!(
            joint(
                &["Ali", "Ayşe", "Mehmet"],
                Type::Conjunction,
                Style::Long,
                "tr"
            ),
            "Ali, Ayşe ve Mehmet"
        );
        assert_eq!(
            joint(
                &["Ali", "Ayşe", "Mehmet"],
                Type::Conjunction,
                Style::Long,
                "de"
            ),
            "Ali, Ayşe und Mehmet"
        );
        assert_eq!(
            joint(
                &["Ali", "Ayşe", "Mehmet"],
                Type::Conjunction,
                Style::Long,
                "ja"
            ),
            "Ali、Ayşe、Mehmet"
        );
    }

    #[test]
    fn parts_are_elements_and_literals_in_order() {
        let locale = locale::resolve(&["en".to_owned()], "en-US");
        let items = ["apples", "oranges", "pears"].map(str::to_owned);
        let parts = format(
            &items,
            &Format {
                kind: Type::Conjunction,
                style: Style::Long,
            },
            &locale.lists,
        );
        let parts: Vec<(&str, &str)> = parts.iter().map(|p| (p.kind, p.value.as_str())).collect();
        assert_eq!(
            parts,
            [
                ("element", "apples"),
                ("literal", ", "),
                ("element", "oranges"),
                ("literal", ", and "),
                ("element", "pears"),
            ]
        );
    }
}