-
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(range): add validator for range
- Loading branch information
1 parent
2bde8c0
commit 77e3004
Showing
4 changed files
with
56 additions
and
0 deletions.
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 |
---|---|---|
|
@@ -16,6 +16,7 @@ export { | |
} from "./validation.ts"; | ||
export { | ||
and, | ||
between, | ||
bigint, | ||
boolean, | ||
count, | ||
|
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,39 @@ | ||
// Copyright 2023-latest Tomoki Miyauchi. All rights reserved. MIT license. | ||
// This module is browser compatible. | ||
|
||
import { isInRange, shouldBeBut } from "./utils.ts"; | ||
import { ScalarValidator } from "../utils.ts"; | ||
|
||
export class RangeValidator<In> extends ScalarValidator<In> { | ||
#range!: [In, In]; | ||
|
||
get range(): [In, In] { | ||
return this.#range; | ||
} | ||
|
||
set range(range) { | ||
if (range[1] <= range[0]) { | ||
throw RangeError("max should be greater than min"); | ||
} | ||
|
||
this.#range = range; | ||
} | ||
|
||
/** | ||
* @throws {RangeError} If {@link max} less than or equal to {@link min}. | ||
*/ | ||
constructor(min: In, max: In) { | ||
super(); | ||
super.expect(shouldBeBut); | ||
|
||
this.range = [min, max]; | ||
} | ||
|
||
override is(input: In): input is In { | ||
return isInRange(input, this.range); | ||
} | ||
|
||
override toString(): string { | ||
return `between ${this.range[0]} and ${this.range[1]}`; | ||
} | ||
} |
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