Skip to content

Commit 99f3592

Browse files
committed
Added: Trim End Characters
1 parent bc7d2c3 commit 99f3592

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import { assertEquals } from "https://deno.land/std@0.203.0/assert/assert_equals.ts";
2+
import trimCharactersStart from "./trim_characters_end.ts";
3+
4+
Deno.test(
5+
'Trim characters at the end of a string.',
6+
async (test) => {
7+
await test.step({
8+
name: 'Empty input string, empty characters',
9+
fn: () => {
10+
assertEquals(
11+
trimCharactersStart('', ''),
12+
''
13+
)
14+
}
15+
})
16+
17+
await test.step({
18+
name: 'Empty characters',
19+
fn: () => {
20+
assertEquals(
21+
trimCharactersStart('abc123', ''),
22+
'abc123'
23+
)
24+
}
25+
})
26+
27+
await test.step({
28+
name: 'Empty input string',
29+
fn: () => {
30+
assertEquals(
31+
trimCharactersStart('', 'abc'),
32+
''
33+
)
34+
}
35+
})
36+
37+
await test.step({
38+
name: 'Fake Escaped characters in input string',
39+
fn: () => {
40+
assertEquals(
41+
trimCharactersStart('\babc123\b', '\b'),
42+
'\babc123'
43+
)
44+
}
45+
})
46+
47+
await test.step({
48+
name: 'Real Escaped characters in input string',
49+
fn: () => {
50+
assertEquals(
51+
trimCharactersStart('abc123t\t', '\t'),
52+
'abc123t'
53+
)
54+
}
55+
})
56+
57+
await test.step({
58+
name: 'Skip characters in input string',
59+
fn: () => {
60+
assertEquals(
61+
trimCharactersStart('abc123', '1'),
62+
'abc123'
63+
)
64+
}
65+
})
66+
67+
await test.step({
68+
name: 'Normal trim',
69+
fn: () => {
70+
assertEquals(
71+
trimCharactersStart('abc123', '312ca'),
72+
'ab'
73+
)
74+
}
75+
})
76+
}
77+
)

src/format/trim_characters_end.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* This function is similar to the standard `String.prototype.trimEnd()` function. With this function, several characters
3+
* can be specified as a string which are then trimmed at the end of the `inputString`.
4+
*
5+
* @param inputString The input string to trim the end
6+
* @param characters The characters to trim
7+
* @returns The trimmed input string
8+
*/
9+
export default function trimCharactersStart(
10+
inputString : string,
11+
characters : string
12+
) : string {
13+
const charactersSet = new Set(characters.split(''));
14+
let endIndex = inputString.length - 1;
15+
16+
while (endIndex >= 0 && charactersSet.has(inputString[endIndex])) {
17+
endIndex--;
18+
}
19+
20+
return inputString.substring(0, endIndex + 1);
21+
}

0 commit comments

Comments
 (0)