Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: add support for negative value to get tail from the string #1749

Merged
merged 2 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/main/java/org/cactoos/text/Sub.java
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,22 @@ public Sub(final Text text, final Func<? super String, Integer> start,
new Mapped(
origin -> {
int begin = start.apply(origin);
if (begin < 0) {
begin = origin.length() + begin;
}
if (begin < 0) {
begin = 0;
}
int finish = end.apply(origin);
if (origin.length() < finish) {
if (finish < 0) {
finish = origin.length() + finish;
}
if (finish > origin.length()) {
finish = origin.length();
}
if (finish < 0) {
finish = 0;
}
return origin.substring(begin, finish);
},
text
Expand Down
27 changes: 27 additions & 0 deletions src/test/java/org/cactoos/text/SubTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,31 @@ void cutTextWithStart() {
).affirm();
}

@Test
void cutTextWithNegativeStart() {
new Assertion<>(
"Can't cut text with negative start",
new Sub("hello world", -5),
new HasString("world")
).affirm();
}

@Test
void cutTextWithNegativeStartAndEnd() {
new Assertion<>(
"Can't cut text with negative start and positive end",
new Sub("hello world", -5, 8),
new HasString("wo")
).affirm();
}

@Test
void cutTextWithNegativeStartAndNegativeEnd() {
new Assertion<>(
"Can't cut text with negative start and negative end",
new Sub("hello world", -5, -2),
new HasString("wor")
).affirm();
}

}
Loading