UNPKG

1.36 kBJavaScriptView Raw
1import { buildMessage, ValidateBy } from '../common/ValidateBy';
2export const ARRAY_UNIQUE = 'arrayUnique';
3/**
4 * Checks if all array's values are unique. Comparison for objects is reference-based.
5 * If null or undefined is given then this function returns false.
6 */
7export 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 * Checks if all array's values are unique. Comparison for objects is reference-based.
18 * If null or undefined is given then this function returns false.
19 */
20export 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//# sourceMappingURL=ArrayUnique.js.map
\No newline at end of file