-
Notifications
You must be signed in to change notification settings - Fork 4
/
algorithms.js
128 lines (118 loc) · 2.72 KB
/
algorithms.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
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
function isLower(char) {
return char >= 0x61 /* 'a' */ && char <= 0x7a /* 'z' */;
}
function isUpper(char) {
return char >= 0x41 /* 'A' */ && char <= 0x5a /* 'Z' */;
}
function isDigit(char) {
return char >= 0x30 /* '0' */ && char <= 0x39 /* '9' */;
}
function toUpper(char) {
return char - 0x20;
}
function toUpperSafe(char) {
if(isLower((char))) {
return char - 0x20;
}
return char;
}
function toLower(char) {
return char + 0x20;
}
export function camelize(str, separator) {
let firstChar = str.charCodeAt(0);
if(isDigit(firstChar) || isUpper(firstChar) || firstChar == separator) {
return str;
}
let out = [];
let changed = false;
if(isUpper(firstChar)) {
changed = true;
out.push(toLower(firstChar));
} else {
out.push(firstChar);
}
let length = str.length;
for(let i = 1; i < length; ++i) {
let c = str.charCodeAt(i);
if(c === separator) {
changed = true;
c = str.charCodeAt(++i);
if(isNaN(c)) {
return str;
}
out.push(toUpperSafe(c))
} else {
out.push(c);
}
}
return changed ? String.fromCharCode.apply(undefined, out) : str;
};
export function decamelize(str, separator) {
let firstChar = str.charCodeAt(0);
if(!isLower(firstChar)) {
return str;
}
let length = str.length;
let changed = false;
let out = [];
for(let i = 0; i < length; ++i) {
let c = str.charCodeAt(i);
if(isUpper(c)) {
out.push(separator);
out.push(toLower(c));
changed = true;
} else {
out.push(c);
}
}
return changed ? String.fromCharCode.apply(undefined, out) : str;
}
export function pascalize(str, separator) {
let firstChar = str.charCodeAt(0);
if(isDigit(firstChar) || firstChar == separator) {
return str;
}
let length = str.length;
let changed = false;
let out = [];
for(let i = 0; i < length; ++i) {
let c = str.charCodeAt(i);
if(c === separator) {
changed = true;
c = str.charCodeAt(++i);
if(isNaN(c)) {
return str;
}
out.push(toUpperSafe(c))
} else if(i === 0 && isLower(c)) {
changed = true;
out.push(toUpper(c));
} else {
out.push(c);
}
}
return changed ? String.fromCharCode.apply(undefined, out) : str;
};
export function depascalize(str, separator) {
let firstChar = str.charCodeAt(0);
if(!isUpper(firstChar)) {
return str;
}
let length = str.length;
let changed = false;
let out = [];
for(let i = 0; i < length; ++i) {
let c = str.charCodeAt(i);
if(isUpper(c)) {
if(i > 0) {
out.push(separator);
}
out.push(toLower(c));
changed = true;
} else {
out.push(c);
}
}
return changed ? String.fromCharCode.apply(undefined, out) : str;
}