Add Parse.defaulted
This commit is contained in:
parent
1baf20f6c0
commit
3252c741ec
3 changed files with 25 additions and 4 deletions
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@endeavorance/parsec",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"author": "Endeavorance",
|
||||
"type": "module",
|
||||
"module": "dist/index.js",
|
||||
|
|
15
src/index.ts
15
src/index.ts
|
@ -102,7 +102,7 @@ export const Parse = {
|
|||
throw MismatchError("NaN", val);
|
||||
},
|
||||
|
||||
instanceOf<T>(classDef: { new(): T }): (val: unknown) => T {
|
||||
instanceOf<T>(classDef: { new (): T }): (val: unknown) => T {
|
||||
return (val: unknown) => {
|
||||
if (val instanceof classDef) {
|
||||
return val;
|
||||
|
@ -223,6 +223,19 @@ export const Parse = {
|
|||
};
|
||||
},
|
||||
|
||||
defaulted<T>(
|
||||
parser: (val: unknown) => T,
|
||||
defaultVal: T,
|
||||
): (val: unknown) => T {
|
||||
return (val: unknown) => {
|
||||
if (val === undefined || val === null) {
|
||||
return defaultVal;
|
||||
}
|
||||
|
||||
return parser(val);
|
||||
};
|
||||
},
|
||||
|
||||
oneOf<T extends Parser<unknown>[]>(
|
||||
parsers: T,
|
||||
shapeName = "Union",
|
||||
|
|
|
@ -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,
|
||||
);
|
||||
});
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue