diff --git a/package.json b/package.json index 07fec59..cd1f625 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@endeavorance/parsec", - "version": "0.3.0", + "version": "0.4.0", "author": "Endeavorance", "type": "module", "module": "dist/index.js", diff --git a/src/index.ts b/src/index.ts index dabd1c7..6877eea 100644 --- a/src/index.ts +++ b/src/index.ts @@ -102,7 +102,7 @@ export const Parse = { throw MismatchError("NaN", val); }, - instanceOf(classDef: { new(): T }): (val: unknown) => T { + instanceOf(classDef: { new (): T }): (val: unknown) => T { return (val: unknown) => { if (val instanceof classDef) { return val; @@ -223,6 +223,19 @@ export const Parse = { }; }, + defaulted( + parser: (val: unknown) => T, + defaultVal: T, + ): (val: unknown) => T { + return (val: unknown) => { + if (val === undefined || val === null) { + return defaultVal; + } + + return parser(val); + }; + }, + oneOf[]>( parsers: T, shapeName = "Union", diff --git a/src/test/parse.test.ts b/src/test/parse.test.ts index a7ad47d..659e91f 100644 --- a/src/test/parse.test.ts +++ b/src/test/parse.test.ts @@ -176,6 +176,14 @@ describe(Parse.nullable, () => { }); }); +describe(Parse.defaulted, () => { + test("Parses uses a default value for undefined params", () => { + expect(Parse.defaulted(Parse.string, "default!")(undefined)).toBe( + "default!", + ); + }); +}); + describe(Parse.nan, () => { test("Parses NaN", () => { expect(Parse.nan(Number.NaN)).toBe(Number.NaN); @@ -189,7 +197,7 @@ describe(Parse.nan, () => { }); }); -class TestClass { } +class TestClass {} describe(Parse.instanceOf, () => { test("Parses instances of a class", () => { @@ -206,7 +214,7 @@ describe(Parse.instanceOf, () => { test("Throws an error when parsing an instance of a different class", () => { const testClass = new TestClass(); - expect(() => Parse.instanceOf(class AnotherClass { })(testClass)).toThrow( + expect(() => Parse.instanceOf(class AnotherClass {})(testClass)).toThrow( ParseError, ); });