From 706bfc7eb2f07d810e00130be003ba7bfc81f2b7 Mon Sep 17 00:00:00 2001 From: Sean May Date: Mon, 16 Jul 2018 01:13:53 -0400 Subject: [PATCH] No, really, though... --- src/guards/guards.ts | 11 +++++++++++ src/operators/operators.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/guards/guards.ts create mode 100644 src/operators/operators.ts diff --git a/src/guards/guards.ts b/src/guards/guards.ts new file mode 100644 index 0000000..8439862 --- /dev/null +++ b/src/guards/guards.ts @@ -0,0 +1,11 @@ +import { ValueTypeGuard } from "../types"; + +const isTypeof = (type: T): ValueTypeGuard => (x: T): x is T => typeof x === typeof type; + +const isString = isTypeof(String()); +const isNumber = isTypeof(Number()); +const isBoolean = isTypeof(Boolean()); + +const isArray = (xs: T[]): xs is T[] => Array.isArray(xs); + +export { isString, isNumber, isBoolean, isArray, isTypeof }; \ No newline at end of file diff --git a/src/operators/operators.ts b/src/operators/operators.ts new file mode 100644 index 0000000..5f893e5 --- /dev/null +++ b/src/operators/operators.ts @@ -0,0 +1,32 @@ +import { TypedTest, Erratic } from "../types"; + +const isNull = (x: Erratic): x is null => x === null; +const isUndefined = (x: Erratic): x is undefined => x === undefined; + +const isErratic = (x: Erratic): x is null | undefined => + isNull(x) || isUndefined(x); + +const and = (...tests: TypedTest[]) => (x: Erratic): x is T => + isErratic(x) ? false : tests.every(test => test(x)); + +const or = (...tests: TypedTest[]) => (x: Erratic): x is T => + isErratic(x) ? false : tests.some(test => test(x)); + +const optional = (test: TypedTest) => (x: Erratic): x is T => + isNull(x) ? false : isUndefined(x) ? true : test(x); + +const nullable = (test: TypedTest) => (x: Erratic): x is T => + isNull(x) ? true : isUndefined(x) ? false : test(x); + +const erratic = (test: TypedTest) => (x: Erratic): x is T => + isErratic(x) ? true : test(x); + +const compose = and; + +const customTest = (test: TypedTest) => (x: Erratic): x is T => + isErratic(x) ? false : test(x); + +const unsafeTest = (test: TypedTest>) => (x: Erratic): x is T => + test(x); + +export { compose, and, or, optional, nullable, erratic, customTest, unsafeTest };