Skip to content

Commit

Permalink
feat(common): add Checks#nonBlankString() utility
Browse files Browse the repository at this point in the history
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 <peter.somogyvari@accenture.com>
  • Loading branch information
petermetz committed Dec 1, 2020
1 parent e50d9ce commit c21c873
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
19 changes: 19 additions & 0 deletions packages/cactus-common/src/main/typescript/checks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,23 @@ export class Checks {
throw new CodedError(message, code);
}
}

/**
* Verifies that a string is indeed not a blank string.
* Blank string can be one that only has whitespace characters for example.
*
* @param value The value that will be asserted for being a non-blank string.
* @param subject The error message if `value` is a blank string.
* @param code The code of the error if `checkResult is falsy.
*/
public static nonBlankString(
value: any,
subject: string = "variable",
code: string = "-1"
): void {
if (typeof value !== "string" || value.trim().length === 0) {
const message = `"${subject}" is a blank string. Need non-blank.`;
throw new CodedError(message, code);
}
}
}
27 changes: 27 additions & 0 deletions packages/cactus-common/src/test/typescript/unit/checks.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import test, { Test } from "tape";

import { v4 as uuidv4 } from "uuid";

import { Checks } from "../../../main/typescript";

test("Checks", (t: Test) => {
test("Checks#nonBlankString()", (t2: Test) => {
const subject = uuidv4();
const pattern = new RegExp(`${subject}`);

t2.throws(() => Checks.nonBlankString("", subject), pattern);
t2.throws(() => Checks.nonBlankString(" ", subject), pattern);
t2.throws(() => Checks.nonBlankString("\n", subject), pattern);
t2.throws(() => Checks.nonBlankString("\t", subject), pattern);
t2.throws(() => Checks.nonBlankString("\t\n", subject), pattern);
t2.throws(() => Checks.nonBlankString("\n\r", subject), pattern);

t2.doesNotThrow(() => Checks.nonBlankString("-"));
t2.doesNotThrow(() => Checks.nonBlankString(" a "));
t2.doesNotThrow(() => Checks.nonBlankString("\na\t"));

t2.end();
});

t.end();
});

0 comments on commit c21c873

Please sign in to comment.