| 4355 | * @since 3.10.0 |
| 4356 | */ |
| 4357 | export const length = <S extends Schema.Any>( |
| 4358 | length: number | { readonly min: number; readonly max: number }, |
| 4359 | annotations?: Annotations.Filter<Schema.Type<S>> |
| 4360 | ) => |
| 4361 | <A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => { |
| 4362 | const minLength = Predicate.isObject(length) ? Math.max(0, Math.floor(length.min)) : Math.max(0, Math.floor(length)) |
| 4363 | const maxLength = Predicate.isObject(length) ? Math.max(minLength, Math.floor(length.max)) : minLength |
| 4364 | if (minLength !== maxLength) { |
| 4365 | return self.pipe( |
| 4366 | filter((a) => a.length >= minLength && a.length <= maxLength, { |
| 4367 | schemaId: LengthSchemaId, |
| 4368 | title: `length({ min: ${minLength}, max: ${maxLength})`, |
| 4369 | description: `a string at least ${minLength} character(s) and at most ${maxLength} character(s) long`, |
| 4370 | jsonSchema: { minLength, maxLength }, |
| 4371 | ...annotations |
| 4372 | }) |
| 4373 | ) |
| 4374 | } |
| 4375 | return self.pipe( |
| 4376 | filter((a) => a.length === minLength, { |
| 4377 | schemaId: LengthSchemaId, |
| 4378 | title: `length(${minLength})`, |
| 4379 | description: minLength === 1 ? `a single character` : `a string ${minLength} character(s) long`, |
| 4380 | jsonSchema: { minLength, maxLength: minLength }, |
| 4381 | ...annotations |
| 4382 | }) |
| 4383 | ) |
| 4384 | } |
| 4385 | |
| 4386 | /** |
| 4387 | * @category schema id |