pub fn slug(name: &str) -> Option<String> {
let mut out = String::new();
for ch in name.trim().chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_lowercase());
} else if ch.is_whitespace() || ch == '-' || ch == '_' {
if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
} else {
return None;
}
}
let out = out.trim_end_matches('-').to_string();
out.starts_with(|c: char| c.is_ascii_lowercase())
.then_some(out)
}
fn words(slug: &str) -> impl Iterator<Item = &str> {
slug.split('-').filter(|w| !w.is_empty())
}
fn capitalised(word: &str) -> String {
let mut chars = word.chars();
match chars.next() {
Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(),
None => String::new(),
}
}
pub fn pascal(slug: &str) -> String {
words(slug).map(capitalised).collect()
}
pub fn camel(slug: &str) -> String {
let mut words = words(slug);
let first = words.next().unwrap_or_default().to_string();
first + &words.map(capitalised).collect::<String>()
}
const RESERVED: &[&str] = &[
"arguments",
"await",
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"eval",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"implements",
"import",
"in",
"instanceof",
"interface",
"let",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"static",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"var",
"void",
"while",
"with",
"yield",
];
pub fn is_reserved(ident: &str) -> bool {
RESERVED.contains(&ident)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slug_kebab_cases_what_was_typed() {
assert_eq!(slug("Plugin Algo").as_deref(), Some("plugin-algo"));
assert_eq!(slug("algo").as_deref(), Some("algo"));
assert_eq!(slug(" Rate Limit ").as_deref(), Some("rate-limit"));
assert_eq!(slug("rate_limit").as_deref(), Some("rate-limit"));
assert_eq!(slug("already-kebab").as_deref(), Some("already-kebab"));
assert_eq!(slug("v2 cache").as_deref(), Some("v2-cache"));
}
#[test]
fn slug_rejects_what_cannot_be_a_name() {
assert_eq!(slug(""), None);
assert_eq!(slug(" "), None);
assert_eq!(slug("--"), None);
assert_eq!(slug("🍵"), None);
assert_eq!(slug("2fa"), None);
assert_eq!(slug("rate.limit"), None);
}
#[test]
fn reserved_words_and_uses_are_found() {
assert!(is_reserved("delete"));
assert!(is_reserved("class"));
assert!(!is_reserved("pluginAlgo"));
}
#[test]
fn identifiers_follow_the_slug() {
assert_eq!(camel("plugin-algo"), "pluginAlgo");
assert_eq!(pascal("plugin-algo"), "PluginAlgo");
assert_eq!(camel("algo"), "algo");
assert_eq!(pascal("v2-cache"), "V2Cache");
}
}