Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate array uniqueness #1

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
- [`.element`](#element)
- [`.nonempty`](#nonempty)
- [`.min/.max/.length`](#minmaxlength)
- [`.unique`](#unique)
- [Tuples](#tuples)
- [Unions](#unions)
- [Discriminated unions](#discriminated-unions)
Expand Down Expand Up @@ -1527,6 +1528,18 @@ z.string().array().length(5); // must contain 5 items exactly

Unlike `.nonempty()` these methods do not change the inferred type.

### `.unique`

```ts
// All elements must be unique
z.object({ id: z.string() }).array().unique();

// All elements must be unique based on the id property
z.object({ id: z.string(), name: z.string() })
.array()
.unique((elt) => elt.id);
```

## Tuples

Unlike arrays, tuples have a fixed number of elements and each element can have a different type.
Expand Down
13 changes: 13 additions & 0 deletions deno/lib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
- [`.element`](#element)
- [`.nonempty`](#nonempty)
- [`.min/.max/.length`](#minmaxlength)
- [`.unique`](#unique)
- [Tuples](#tuples)
- [Unions](#unions)
- [Discriminated unions](#discriminated-unions)
Expand Down Expand Up @@ -1527,6 +1528,18 @@ z.string().array().length(5); // must contain 5 items exactly

Unlike `.nonempty()` these methods do not change the inferred type.

### `.unique`

```ts
// All elements must be unique
z.object({ id: z.string() }).array().unique();

// All elements must be unique based on the id property
z.object({ id: z.string(), name: z.string() })
.array()
.unique((elt) => elt.id);
```

## Tuples

Unlike arrays, tuples have a fixed number of elements and each element can have a different type.
Expand Down
44 changes: 12 additions & 32 deletions deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1985,8 +1985,10 @@ export interface ZodArrayDef<T extends ZodTypeAny = ZodTypeAny>
minLength: { value: number; message?: string } | null;
maxLength: { value: number; message?: string } | null;
uniqueness: {
identifier?: ArrayUniqueIdentifier;
message?: string | ArrayMessageFunction;
identifier?: <U extends T["_output"]>(item: U) => unknown;
message?:
| string
| (<U extends T["_output"]>(duplicateItems: U[]) => string);
showDuplicates?: boolean;
} | null;
}
Expand All @@ -1998,10 +2000,6 @@ export type arrayOutputType<
> = Cardinality extends "atleastone"
? [T["_output"], ...T["_output"][]]
: T["_output"][];
type ArrayMessageFunction<T extends ZodTypeAny = ZodTypeAny> = (
duplicateElements: Array<T["_output"]>
) => string;
type ArrayUniqueIdentifier<T = any> = (o: T) => unknown;

export class ZodArray<
T extends ZodTypeAny,
Expand Down Expand Up @@ -2074,18 +2072,17 @@ export class ZodArray<

if (def.uniqueness !== null) {
const { identifier, message, showDuplicates } = def.uniqueness;

const result = this._arrayUnique(ctx.data, identifier, showDuplicates);
const { unique, duplicateElements } = result;

if (!unique) {
const duplicates = (
identifier
? (ctx.data as this["_output"][]).map(identifier)
: (ctx.data as this["_output"][])
).filter((item, idx, arr) => arr.indexOf(item) !== idx);
if (duplicates.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.uniqueness,
duplicateElements,
duplicateElements: showDuplicates ? duplicates : undefined,
message:
typeof message === "function"
? message(duplicateElements)
: message,
typeof message === "function" ? message(duplicates) : message,
});
status.dirty();
}
Expand Down Expand Up @@ -2116,23 +2113,6 @@ export class ZodArray<
return this._def.type;
}

_arrayUnique(
array: Array<T["_output"]>,
identifier?: ArrayUniqueIdentifier<T["_output"]>,
showDuplicates = false
) {
if (identifier) {
array = array.map((o) => (o != null ? identifier(o) : o));
}

return {
unique: array.length === new Set(array).size,
duplicateElements: showDuplicates
? array.filter((item, index) => array.indexOf(item) !== index)
: [],
};
}

min(minLength: number, message?: errorUtil.ErrMessage): this {
return new ZodArray({
...this._def,
Expand Down
44 changes: 12 additions & 32 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1985,8 +1985,10 @@ export interface ZodArrayDef<T extends ZodTypeAny = ZodTypeAny>
minLength: { value: number; message?: string } | null;
maxLength: { value: number; message?: string } | null;
uniqueness: {
identifier?: ArrayUniqueIdentifier;
message?: string | ArrayMessageFunction;
identifier?: <U extends T["_output"]>(item: U) => unknown;
message?:
| string
| (<U extends T["_output"]>(duplicateItems: U[]) => string);
showDuplicates?: boolean;
} | null;
}
Expand All @@ -1998,10 +2000,6 @@ export type arrayOutputType<
> = Cardinality extends "atleastone"
? [T["_output"], ...T["_output"][]]
: T["_output"][];
type ArrayMessageFunction<T extends ZodTypeAny = ZodTypeAny> = (
duplicateElements: Array<T["_output"]>
) => string;
type ArrayUniqueIdentifier<T = any> = (o: T) => unknown;

export class ZodArray<
T extends ZodTypeAny,
Expand Down Expand Up @@ -2074,18 +2072,17 @@ export class ZodArray<

if (def.uniqueness !== null) {
const { identifier, message, showDuplicates } = def.uniqueness;

const result = this._arrayUnique(ctx.data, identifier, showDuplicates);
const { unique, duplicateElements } = result;

if (!unique) {
const duplicates = (
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TIP: That part could be rewritten only for reading purposes, this way:

const output = (ctx.data as this["_output"][]);
const duplicates = (identifier ? output.map(identifier) : output).filter((item, idx, arr) => arr.indexOf(item) !== idx);

identifier
? (ctx.data as this["_output"][]).map(identifier)
: (ctx.data as this["_output"][])
).filter((item, idx, arr) => arr.indexOf(item) !== idx);
if (duplicates.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.uniqueness,
duplicateElements,
duplicateElements: showDuplicates ? duplicates : undefined,
message:
typeof message === "function"
? message(duplicateElements)
: message,
typeof message === "function" ? message(duplicates) : message,
});
status.dirty();
}
Expand Down Expand Up @@ -2116,23 +2113,6 @@ export class ZodArray<
return this._def.type;
}

_arrayUnique(
array: Array<T["_output"]>,
identifier?: ArrayUniqueIdentifier<T["_output"]>,
showDuplicates = false
) {
if (identifier) {
array = array.map((o) => (o != null ? identifier(o) : o));
}

return {
unique: array.length === new Set(array).size,
duplicateElements: showDuplicates
? array.filter((item, index) => array.indexOf(item) !== index)
: [],
};
}

min(minLength: number, message?: errorUtil.ErrMessage): this {
return new ZodArray({
...this._def,
Expand Down