-
Notifications
You must be signed in to change notification settings - Fork 0
/
pretty-capitalize.js
70 lines (58 loc) · 1.59 KB
/
pretty-capitalize.js
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
const ALPHABET = /[a-zA-Z']+/g
const MINOR_WORDS = new Set([
'of',
'a',
'an',
'in',
'the',
'as',
'and',
'or',
'of',
'with',
'by',
'for',
'to'
])
function isMinorWord (word) {
return MINOR_WORDS.has(word.toLowerCase())
}
function maybeIsAcronym (word) {
return word.toUpperCase() === word
}
function capitalizeWord (word, force = false) {
if (maybeIsAcronym(word)) return word
if (!force && isMinorWord(word)) return word.toLowerCase()
return word[0].toUpperCase() + word.substr(1).toLowerCase()
}
function prettyCapitalize (text) {
const parts = text.match(ALPHABET)
for (let i = 0; i < parts.length; i++) {
parts[i] = capitalizeWord(parts[i], i === 0)
}
let result = ''
for (let i = 0, j = 0; i < text.length;) {
if (text[i].match(ALPHABET) !== null) {
result += parts[j]
i += parts[j].length
j++
} else {
result += text[i]
i++
}
}
return result
}
console.assert(maybeIsAcronym('BFS'))
console.assert(maybeIsAcronym('DFS'))
console.assert(prettyCapitalize(' ford and Fulkerson ') === ' Ford and Fulkerson ')
console.assert(prettyCapitalize(' ford & Fulkerson ') === ' Ford & Fulkerson ')
console.assert(prettyCapitalize(' ford & Fulkerson ') === ' Ford & Fulkerson ')
console.assert(prettyCapitalize(' just use DFS or BFS ') === ' Just Use DFS or BFS ')
console.assert(prettyCapitalize('BIT And segtree') === 'BIT and Segtree')
console.assert(prettyCapitalize(' and you??? ') === ' And You??? ')
console.assert(isMinorWord('of'))
console.assert(!isMinorWord('hello'))
module.exports = {
prettyCapitalize
}