-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcamel_case.rs
77 lines (65 loc) · 2.04 KB
/
camel_case.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//! Converts `String` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
//!
//! Example
//! ```
//! use lodash_rust::camel_case;
//!
//!
//! let value = String::from("enable 6h format");
//! let res = camel_case::new(value);
//! println!("{res}") // enable6HFormat
//!
//! ```
extern crate regex;
use camel_case::regex::Captures;
pub fn new(string: String) -> String {
//regex to substitute
let re = regex::Regex::new(
r"(?x)
(?P<cut>[^a-zA-Z\d]+) # every char not in camelCase
(?:
(?P<replace>
\d+[a-zA-Z] # example: 24h
|
\d+ # example: 500
|
[a-zA-Z] # example: format
)
|$)",
)
.unwrap();
let prep = string.to_lowercase();
let ret = re.replace_all(&prep, |caps: &Captures| {
caps.get(2)
.map(|n| n.as_str())
.unwrap_or("")
.to_uppercase()
.to_string()
});
if ret.chars().next().map(|c| !c.is_ascii()).unwrap_or(true) {
return ret.to_string(); //error handling for when String size is less than two
}
let tail = &ret[1..];
format!("{}{tail}", ret.chars().next().unwrap().to_lowercase())
}
#[test]
fn test_new() {
let test_one = String::from("12 feet");
assert_eq!(new(test_one), "12Feet");
let test_two = String::from("enable 6h format");
assert_eq!(new(test_two), "enable6HFormat");
let test_three = String::from("enable 24H format");
assert_eq!(new(test_three), "enable24HFormat");
let test_four = String::from("too legit 2 quit");
assert_eq!(new(test_four), "tooLegit2Quit");
let test_five = String::from("walk 500 miles");
assert_eq!(new(test_five), "walk500Miles");
let test_six = String::from("xhr2 request");
assert_eq!(new(test_six), "xhr2Request");
let test_seven = String::from("--xhr--request--");
assert_eq!(new(test_seven), "xhrRequest");
let test_eight = String::from("__FOO_BAR__");
assert_eq!(new(test_eight), "fooBar");
let test_nine = String::from("foo 2000_ha");
assert_eq!(new(test_nine), "foo2000Ha");
}