Skip to content

Commit 65b97bf

Browse files
committed
feat(not): add validator for logical not operator
1 parent 63d8d2f commit 65b97bf

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

combinator.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { GreaterThenValidator } from "./validators/operators/gt.ts";
2323
import { GreaterThenOrEqualValidator } from "./validators/operators/gte.ts";
2424
import { InequalityValidator } from "./validators/operators/inequality.ts";
2525
import { InstanceValidator } from "./validators/operators/instanceof.ts";
26+
import { NotValidator } from "./validators/operators/not.ts";
2627
import { OrValidator } from "./validators/operators/or.ts";
2728
import { TypeValidator } from "./validators/operators/typeof.ts";
2829
import { ValidDateValidator } from "./validators/date/valid_date.ts";
@@ -42,6 +43,7 @@ export const lte = /* @__PURE__ */ lazy(LessThenOrEqualValidator);
4243
export const gt = /* @__PURE__ */ lazy(GreaterThenValidator);
4344
export const gte = /* @__PURE__ */ lazy(GreaterThenOrEqualValidator);
4445
export const ne = /* @__PURE__ */ lazy(InequalityValidator);
46+
export const not = /* @__PURE__ */ lazy(NotValidator);
4547
export const or = /* @__PURE__ */ lazy(OrValidator);
4648
export const and = /* @__PURE__ */ lazy(AndValidator);
4749

mod.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export {
2020
minCount,
2121
ne,
2222
nonEmpty,
23+
not,
2324
nullish,
2425
number,
2526
object,

validators/operators/not.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Copyright 2023-latest Tomoki Miyauchi. All rights reserved. MIT license.
2+
// This module is browser compatible.
3+
4+
import { shouldBeBut } from "../utils.ts";
5+
import { Reporter, ValidationFailure, Validator } from "../../types.ts";
6+
7+
export interface ReportContext<In = unknown> {
8+
input: In;
9+
}
10+
11+
export class NotValidator<in In = unknown, In_ extends In = In>
12+
extends Reporter<ReportContext<In>>
13+
implements Validator<In, In_> {
14+
validator: Validator<In, In_>;
15+
16+
constructor(validator: Validator<In, In_>) {
17+
super();
18+
super.expect(shouldBeBut);
19+
this.validator = validator;
20+
}
21+
22+
is(input: In): input is In_ {
23+
return !this.validator.is(input);
24+
}
25+
26+
*validate(input: In): Iterable<ValidationFailure> {
27+
if (!this.is(input)) yield new ValidationFailure(this.report({ input }));
28+
}
29+
30+
override toString(): string {
31+
return `not ${this.validator}`;
32+
}
33+
}

0 commit comments

Comments
 (0)