Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 10x 10x 1x 4x 7x 7x 3x | import { Validator } from "../types";
import { isValid } from "../utils";
/**
* Creates a validator accepting arrays
* and runs provided item validator against every array item.
* Returns an object where keys are indices of array items having validation errors.
*
* @example
*
* ```ts
* import { object, compose, string, required, number, min } from 'compose-validators';
*
* const person = object({
* name: compose(string, required),
* age: compose(number, min(18)),
* })
*
* const people = arrayOf(person);
*
* people([
* { name: 'John', age: 30 },
* { name: 'Jim', age: 15 },
* ])
* // this returns
* // {
* // 1: { age: { min: 18 } }
* // }
* ```
* @typeParam Item Type of array item
*
* @param validator Array item validator
*/
export const arrayOf = <Item>(
validator: Validator<Item>
): Validator<Item[]> => (value: Item[]) => {
return value.reduce((acc, item, index) => {
const result = validator(item);
if (isValid(result)) return acc;
return { ...acc, [index]: result };
}, {});
};
|