Skip to content

Commit 231bac3

Browse files
committed
Improve performance of enum schema by caching values
1 parent afcab01 commit 231bac3

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

library/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ All notable changes to the library will be documented in this file.
44

55
## vX.X.X (Month DD, YYYY)
66

7+
- Improve performance of `enum_` and `enumAsync` schema by caching values
78
- Fix bug in `getDefaults`, `getDefaultsAsync`, `getFallbacks` and `getFallbacksAsync` for falsy but not `undefined` values (issue #356)
89

910
## v0.25.0 (December 26, 2023)

library/src/schemas/enum/enum.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,21 @@ export function enum_<TEnum extends Enum>(
4242
enum_: TEnum,
4343
message: ErrorMessage = 'Invalid type'
4444
): EnumSchema<TEnum> {
45+
// Create cached values
46+
let cachedValues: (string | number)[];
47+
48+
// Create and return enum schema
4549
return {
4650
type: 'enum',
4751
async: false,
4852
enum: enum_,
4953
message,
5054
_parse(input, info) {
55+
// Cache values lazy
56+
cachedValues = cachedValues || Object.values(this.enum);
57+
5158
// Check type of input
52-
if (!Object.values(this.enum).includes(input as any)) {
59+
if (!cachedValues.includes(input as any)) {
5360
return schemaIssue(info, 'type', 'enum', this.message, input);
5461
}
5562

library/src/schemas/enum/enumAsync.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,21 @@ export function enumAsync<TEnum extends Enum>(
3535
enum_: TEnum,
3636
message: ErrorMessage = 'Invalid type'
3737
): EnumSchemaAsync<TEnum> {
38+
// Create cached values
39+
let cachedValues: (string | number)[];
40+
41+
// Create and return enum schema
3842
return {
3943
type: 'enum',
4044
async: true,
4145
enum: enum_,
4246
message,
4347
async _parse(input, info) {
48+
// Cache values lazy
49+
cachedValues = cachedValues || Object.values(this.enum);
50+
4451
// Check type of input
45-
if (!Object.values(this.enum).includes(input as any)) {
52+
if (!cachedValues.includes(input as any)) {
4653
return schemaIssue(info, 'type', 'enum', this.message, input);
4754
}
4855

0 commit comments

Comments
 (0)