-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(or): add validator for logical or operator
- Loading branch information
1 parent
caee113
commit 63d8d2f
Showing
3 changed files
with
52 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -24,6 +24,7 @@ export { | |
number, | ||
object, | ||
optional, | ||
or, | ||
pattern, | ||
positive, | ||
property, | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// Copyright 2023-latest Tomoki Miyauchi. All rights reserved. MIT license. | ||
// This module is browser compatible. | ||
|
||
import { isEmpty } from "../../deps.ts"; | ||
import { displayOr, shouldBe } from "../utils.ts"; | ||
import { Reporter, ValidationFailure, Validator } from "../../types.ts"; | ||
import { iter } from "../../iter_utils.ts"; | ||
|
||
export interface ReportContext<In = unknown> { | ||
input: In; | ||
} | ||
|
||
export class OrValidator<in In = unknown, In_ extends In = In> | ||
extends Reporter<ReportContext<In>> | ||
implements Validator<In, In_> { | ||
validators: [Validator<In, In_>, Validator<In, In_>, ...Validator<In, In_>[]]; | ||
|
||
constructor( | ||
left: Validator<In, In_>, | ||
right: Validator<In, In_>, | ||
...validations: Validator<In, In_>[] | ||
) { | ||
super(); | ||
this.expect(shouldBe); | ||
this.validators = [left, right, ...validations]; | ||
} | ||
|
||
is(input: In): input is In_ { | ||
return isEmpty(this.validate(input)); | ||
} | ||
|
||
*validate(input: In): Iterable<ValidationFailure> { | ||
for (const validator of this.validators) { | ||
const iterable = validator.validate(input); | ||
|
||
if (iter(iterable).done) return; | ||
} | ||
|
||
const context: ReportContext<In> = { input }; | ||
const message = this.report(context); | ||
|
||
yield new ValidationFailure(message); | ||
} | ||
|
||
override toString(): string { | ||
return displayOr(...this.validators); | ||
} | ||
} |