Skip to content

Commit 725eb05

Browse files
committed
use helper functions
1 parent 5158096 commit 725eb05

File tree

1 file changed

+14
-31
lines changed

1 file changed

+14
-31
lines changed

src/validation.ts

Lines changed: 14 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ function success<T>(t: T): ValidationResult<T> {
2424
value: t,
2525
};
2626
}
27+
2728
function failure<T>(errors: IValidationError[]): ValidationResult<T> {
2829
return {
2930
success: false,
@@ -100,33 +101,24 @@ export function object<S>(schema: { [P in keyof S]: Validator<S[P]> }): Validato
100101
}
101102

102103
if (!validationFailed) {
103-
return {
104-
success: true,
105-
// when we get here, all properties in S have been validated and assigned, so
106-
// this type assertion is okay.
107-
value: scrutinee as { [P in keyof S]: S[P] },
108-
};
104+
// when we get here, all properties in S have been validated and assigned, so
105+
// this type assertion is okay.
106+
return success(scrutinee as { [P in keyof S]: S[P] });
109107
}
110108

111-
return {
112-
success: false,
113-
errors,
114-
};
109+
return failure(errors);
115110
};
116111
}
117112

118113
export function array<S>(memberValidator: Validator<S>): Validator<S[]> {
119114
return (scrutinee) => {
120115
if (!(scrutinee instanceof Array)) {
121-
return {
122-
success: false,
123-
errors: [
124-
{
125-
path: [],
126-
message: 'expected an array',
127-
},
128-
],
129-
};
116+
return failure([
117+
{
118+
path: [],
119+
message: 'expected an array',
120+
},
121+
]);
130122
}
131123

132124
const errors: IValidationError[] = [];
@@ -147,26 +139,17 @@ export function array<S>(memberValidator: Validator<S>): Validator<S[]> {
147139
}
148140

149141
if (!validationFailed) {
150-
return {
151-
success: true,
152-
value: scrutinee,
153-
};
142+
return success(scrutinee);
154143
}
155144

156-
return {
157-
success: false,
158-
errors,
159-
};
145+
return failure(errors);
160146
};
161147
}
162148

163149
export function optional<T>(validator: Validator<T>): Validator<T | null> {
164150
return (scrutinee) => {
165151
if (scrutinee === null) {
166-
return {
167-
success: true,
168-
value: null,
169-
};
152+
return success(null);
170153
}
171154
return validator(scrutinee);
172155
};

0 commit comments

Comments
 (0)