-
Notifications
You must be signed in to change notification settings - Fork 1
/
justin.gleam
139 lines (126 loc) · 2.45 KB
/
justin.gleam
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import gleam/string
import gleam/list
/// Convert a string to a `snake_case`.
///
/// # Examples
///
/// ```gleam
/// snake_case("Hello World")
/// // -> "hello_world"
/// ```
///
pub fn snake_case(text: String) -> String {
text
|> split_words
|> string.join("_")
|> string.lowercase
}
/// Convert a string to a `camelCase`.
///
/// # Examples
///
/// ```gleam
/// camel_case("Hello World")
/// // -> "helloWorld"
/// ```
///
pub fn camel_case(text: String) -> String {
text
|> split_words
|> list.index_map(fn(word, i) {
case i {
0 -> string.lowercase(word)
_ -> string.capitalise(word)
}
})
|> string.concat
}
/// Convert a string to a `PascalCase`.
///
/// # Examples
///
/// ```gleam
/// pascal_case("Hello World")
/// // -> "HelloWorld"
/// ```
///
pub fn pascal_case(text: String) -> String {
text
|> split_words
|> list.map(string.capitalise)
|> string.concat
}
/// Convert a string to a `kebab-case`.
///
/// # Examples
///
/// ```gleam
/// kabab_case("Hello World")
/// // -> "hello-world
/// ```
///
pub fn kebab_case(text: String) -> String {
text
|> split_words
|> string.join("-")
|> string.lowercase
}
/// Convert a string to a `Sentence case`.
///
/// # Examples
///
/// ```gleam
/// sentence_case("hello-world")
/// // -> "Hello world
/// ```
///
pub fn sentence_case(text: String) -> String {
text
|> split_words
|> string.join(" ")
|> string.capitalise
}
fn split_words(text: String) -> List(String) {
text
|> string.to_graphemes
|> split(False, "", [])
}
fn split(
in: List(String),
up: Bool,
word: String,
words: List(String),
) -> List(String) {
case in {
[] if word == "" -> list.reverse(words)
[] -> list.reverse(add(words, word))
["\n", ..in]
| ["\t", ..in]
| ["!", ..in]
| ["?", ..in]
| ["#", ..in]
| [".", ..in]
| ["-", ..in]
| ["_", ..in]
| [" ", ..in] -> split(in, False, "", add(words, word))
[g, ..in] -> {
case is_upper(g) {
// Lowercase, not a new word
False -> split(in, False, word <> g, words)
// Uppercase and inside an uppercase word, not a new word
True if up -> split(in, up, word <> g, words)
// Uppercase otherwise, a new word
True -> split(in, True, g, add(words, word))
}
}
}
}
fn add(words: List(String), word: String) -> List(String) {
case word {
"" -> words
_ -> [word, ..words]
}
}
fn is_upper(g: String) -> Bool {
string.lowercase(g) != g
}