-
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(unique): add validator for unique item
- Loading branch information
1 parent
de6059a
commit 0d34889
Showing
3 changed files
with
49 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 |
---|---|---|
|
@@ -24,5 +24,6 @@ export { | |
positive, | ||
string, | ||
type, | ||
unique, | ||
validDate, | ||
} from "./combinator.ts"; |
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,46 @@ | ||
// Copyright 2023-latest Tomoki Miyauchi. All rights reserved. MIT license. | ||
// This module is browser compatible. | ||
|
||
import { enumerate } from "../../iter_utils.ts"; | ||
import { display, interpolate } from "../../utils.ts"; | ||
import { Reporter, ValidationError, Validator } from "../../types.ts"; | ||
import error from "../error.json" assert { type: "json" }; | ||
|
||
interface Context { | ||
input: Iterable<unknown>; | ||
index: number; | ||
item: unknown; | ||
} | ||
|
||
@display("unique") | ||
export class UniqueValidator extends Reporter<Context> | ||
implements Validator<Iterable<unknown>> { | ||
constructor() { | ||
super(); | ||
super.expect(({ item }) => interpolate(error.unique, [item])); | ||
} | ||
*validate(input: Iterable<unknown>): Iterable<ValidationError> { | ||
for (const [index, item] of duplicates(input)) { | ||
yield new ValidationError( | ||
this.report({ input, item, index }), | ||
{ | ||
instancePath: [index.toString()], | ||
}, | ||
); | ||
} | ||
} | ||
} | ||
|
||
function* duplicates<T>( | ||
iterable: Iterable<T>, | ||
): Iterable<[index: number, item: T]> { | ||
const seen = new Set<T>(); | ||
|
||
for (const [i, item] of enumerate(iterable)) { | ||
if (seen.has(item)) { | ||
yield [i, item]; | ||
} else { | ||
seen.add(item); | ||
} | ||
} | ||
} |