mauss
Version:
lightweight, modular, type-safe utilities
56 lines (55 loc) • 1.66 kB
JavaScript
/**
* A guard for exhaustive checks with `if`/`else`/`switch` statements, this will help branching logic in consuming enumeration and union types.
*
* @example
*
* ```typescript
* import { bulwark } from 'mauss/guards';
*
* let key = 'a' as 'a' | 'z';
* switch (key) {
* case 'a':
* return key.charCodeAt();
* default:
* // Argument of type 'string' is not assignable to parameter of type 'never'.
* return bulwark(key);
* }
* ```
*/
export function bulwark(nothing) {
throw new Error(`UncaughtError: reached forbidden guard with ${JSON.stringify(nothing)}`);
}
/** @returns true if input is not `nullish` or an empty string */
export function exists(i) {
return !nullish(i) && i !== '';
}
/** @returns true if input is `null` or `undefined` */
export function nullish(i) {
return i == null;
}
/** @returns true if input is truthy in general */
export function truthy(i) {
return !!i;
}
// number guards
/** @returns true if input exists or is a number greater than 0 */
export function natural(i) {
return typeof i === 'number' ? i > 0 : exists(i);
}
/** @returns true if input exists or is a number greater than or equal to 0 */
export function whole(i) {
return typeof i === 'number' ? i >= 0 : exists(i);
}
/** @returns negation of the guard function passed, e.g. `not(nullish)` */
export function not(fn) {
return (i) => !fn(i);
}
// string guards
/** @returns true if string input is all lowercase letters */
export function lowercase(s) {
return s === s.toLowerCase();
}
/** @returns true if string input is all uppercase letters */
export function uppercase(s) {
return s === s.toUpperCase();
}