Skip to content

Commit c21c873

Browse files
committed
feat(common): add Checks#nonBlankString() utility
Asserts that a string is not a blank one. Handy when you do not just need to know that something is truthy but also that it is not an empty string or one that only contains whitespaces (which is still a blank one) Signed-off-by: Peter Somogyvari <[email protected]>
1 parent e50d9ce commit c21c873

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

packages/cactus-common/src/main/typescript/checks.ts

+19
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,23 @@ export class Checks {
1818
throw new CodedError(message, code);
1919
}
2020
}
21+
22+
/**
23+
* Verifies that a string is indeed not a blank string.
24+
* Blank string can be one that only has whitespace characters for example.
25+
*
26+
* @param value The value that will be asserted for being a non-blank string.
27+
* @param subject The error message if `value` is a blank string.
28+
* @param code The code of the error if `checkResult is falsy.
29+
*/
30+
public static nonBlankString(
31+
value: any,
32+
subject: string = "variable",
33+
code: string = "-1"
34+
): void {
35+
if (typeof value !== "string" || value.trim().length === 0) {
36+
const message = `"${subject}" is a blank string. Need non-blank.`;
37+
throw new CodedError(message, code);
38+
}
39+
}
2140
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import test, { Test } from "tape";
2+
3+
import { v4 as uuidv4 } from "uuid";
4+
5+
import { Checks } from "../../../main/typescript";
6+
7+
test("Checks", (t: Test) => {
8+
test("Checks#nonBlankString()", (t2: Test) => {
9+
const subject = uuidv4();
10+
const pattern = new RegExp(`${subject}`);
11+
12+
t2.throws(() => Checks.nonBlankString("", subject), pattern);
13+
t2.throws(() => Checks.nonBlankString(" ", subject), pattern);
14+
t2.throws(() => Checks.nonBlankString("\n", subject), pattern);
15+
t2.throws(() => Checks.nonBlankString("\t", subject), pattern);
16+
t2.throws(() => Checks.nonBlankString("\t\n", subject), pattern);
17+
t2.throws(() => Checks.nonBlankString("\n\r", subject), pattern);
18+
19+
t2.doesNotThrow(() => Checks.nonBlankString("-"));
20+
t2.doesNotThrow(() => Checks.nonBlankString(" a "));
21+
t2.doesNotThrow(() => Checks.nonBlankString("\na\t"));
22+
23+
t2.end();
24+
});
25+
26+
t.end();
27+
});

0 commit comments

Comments
 (0)