1 | import { buildMessage, ValidateBy } from '../common/ValidateBy';
|
2 | export const ARRAY_UNIQUE = 'arrayUnique';
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | export function arrayUnique(array, identifier) {
|
8 | if (!Array.isArray(array))
|
9 | return false;
|
10 | if (identifier) {
|
11 | array = array.map(o => (o != null ? identifier(o) : o));
|
12 | }
|
13 | const uniqueItems = array.filter((a, b, c) => c.indexOf(a) === b);
|
14 | return array.length === uniqueItems.length;
|
15 | }
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | export function ArrayUnique(identifierOrOptions, validationOptions) {
|
21 | const identifier = typeof identifierOrOptions === 'function' ? identifierOrOptions : undefined;
|
22 | const options = typeof identifierOrOptions !== 'function' ? identifierOrOptions : validationOptions;
|
23 | return ValidateBy({
|
24 | name: ARRAY_UNIQUE,
|
25 | validator: {
|
26 | validate: (value, args) => arrayUnique(value, identifier),
|
27 | defaultMessage: buildMessage(eachPrefix => eachPrefix + "All $property's elements must be unique", options),
|
28 | },
|
29 | }, options);
|
30 | }
|
31 |
|
\ | No newline at end of file |