-
Notifications
You must be signed in to change notification settings - Fork 7
/
camelcase.libsonnet
100 lines (93 loc) · 2.96 KB
/
camelcase.libsonnet
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
local xtd = import './main.libsonnet';
local d = import 'github.com/jsonnet-libs/docsonnet/doc-util/main.libsonnet';
{
'#': d.pkg(
name='camelcase',
url='github.com/jsonnet-libs/xtd/camelcase.libsonnet',
help='`camelcase` can split camelCase words into an array of words.',
),
'#split':: d.fn(
|||
`split` splits a camelcase word and returns an array of words. It also supports
digits. Both lower camel case and upper camel case are supported. It only supports
ASCII characters.
For more info please check: http://en.wikipedia.org/wiki/CamelCase
Based on https://github.com/fatih/camelcase/
|||,
[d.arg('src', d.T.string)]
),
split(src):
if src == ''
then ['']
else
local runes = std.foldl(
function(acc, r)
acc {
local class =
if xtd.ascii.isNumber(r)
then 1
else if xtd.ascii.isLower(r)
then 2
else if xtd.ascii.isUpper(r)
then 3
else 4,
lastClass:: class,
runes:
if class == super.lastClass
then super.runes[:std.length(super.runes) - 1]
+ [super.runes[std.length(super.runes) - 1] + r]
else super.runes + [r],
},
[src[i] for i in std.range(0, std.length(src) - 1)],
{ lastClass:: 0, runes: [] }
).runes;
local fixRunes =
std.foldl(
function(runes, i)
if xtd.ascii.isUpper(runes[i][0])
&& xtd.ascii.isLower(runes[i + 1][0])
&& !xtd.ascii.isNumber(runes[i + 1][0])
&& runes[i][0] != ' '
&& runes[i + 1][0] != ' '
then
std.mapWithIndex(
function(index, r)
if index == i + 1
then runes[i][std.length(runes[i]) - 1:] + r
else
if index == i
then r[:std.length(r) - 1]
else r
, runes
)
else runes
,
[i for i in std.range(0, std.length(runes) - 2)],
runes
);
[
r
for r in fixRunes
if r != ''
],
'#toCamelCase':: d.fn(
|||
`toCamelCase` transforms a string to camelCase format, splitting words by the `-`, `_` or spaces.
For example: `hello_world` becomes `helloWorld`.
For more info please check: http://en.wikipedia.org/wiki/CamelCase
|||,
[d.arg('str', d.T.string)]
),
toCamelCase(str)::
local separators = std.set(std.findSubstr('_', str) + std.findSubstr('-', str) + std.findSubstr(' ', str));
local n = std.join('', [
if std.setMember(i - 1, separators)
then std.asciiUpper(str[i])
else str[i]
for i in std.range(0, std.length(str) - 1)
if !std.setMember(i, separators)
]);
if std.length(n) == 0
then n
else std.asciiLower(n[0]) + n[1:],
}