Skip to content

Commit f80bc60

Browse files
committed
drop_slash: simplify and add tests
1 parent 37c123c commit f80bc60

File tree

2 files changed

+36
-15
lines changed

2 files changed

+36
-15
lines changed

+stdlib/drop_slash.m

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,16 @@
88
p {mustBeTextScalar}
99
end
1010

11-
s = stdlib.posix(p);
12-
13-
uncslash = ispc() && startsWith(s, '//');
14-
1511
% drop repeated slashes inside string
16-
d = regexprep(s, '/+', '/');
17-
18-
L = strlength(d);
12+
d = regexprep(char(p), '/+', '/');
1913

20-
if L < 2
21-
if uncslash
22-
d = '//';
23-
end
24-
elseif ~ispc() || (L ~= 3 || ~strcmp(d, stdlib.root(s)))
25-
d = regexprep(d, '/$', '');
14+
% drop trailing slash "/" or "\", but preserve a single slash if that's the only character
15+
while strlength(d) > 1 && endsWith(d, {'/', '\'})
16+
d = d(1:end-1);
2617
end
2718

28-
if uncslash
29-
d = strcat('/', d);
19+
if ispc() && ~isempty(d) && strcmp(d, stdlib.root_name(p))
20+
d = strcat(d, '/');
3021
end
3122

3223
if isstring(p)

test/TestNormalize.m

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,18 @@
22

33
properties (TestParameter)
44
p = init_norm()
5+
d = init_drop_slash()
56
end
67

78
methods (Test)
89
function test_normalize(tc, p)
910
tc.verifyEqual(stdlib.normalize(p{1}), p{2})
1011
end
12+
13+
function test_drop_slash(tc, d)
14+
tc.verifyEqual(stdlib.drop_slash(d{1}), d{2})
15+
end
16+
1117
end
1218

1319
end
@@ -38,3 +44,27 @@ function test_normalize(tc, p)
3844
p{3}{2} = "//a/b";
3945
end
4046
end
47+
48+
49+
function d = init_drop_slash()
50+
d = {...
51+
{"", ""}, ...
52+
{'a', 'a'}, ...
53+
{"a/", "a"}, ...
54+
{"a/b", "a/b"}, ...
55+
{"a/b/", "a/b"}, ...
56+
{"////", "/"}, ...
57+
{"a////b", "a/b"}, ...
58+
{"a//b//", "a/b"}, ...
59+
{"///", "/"}, ...
60+
{'/', '/'}};
61+
if ispc()
62+
dd = {...
63+
{"c:/", "c:/"}, ...
64+
{"c://", "c:/"}, ...
65+
{"c:///a/b//", "c:/a/b"}, ...
66+
{"c:/a/b//", "c:/a/b"}
67+
};
68+
d = [d, dd];
69+
end
70+
end

0 commit comments

Comments
 (0)