UNPKG

class-validator-extended

Version:
49 lines (48 loc) 1.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayMonotonic = arrayMonotonic; const array_monotonic_options_1 = require("./array-monotonic.options"); function checkMonotonicity(value, monotonicity) { switch (monotonicity) { case array_monotonic_options_1.Monotonicity.WEAKLY_INCREASING: { return value >= 0; } case array_monotonic_options_1.Monotonicity.STRICTLY_INCREASING: { return value > 0; } case array_monotonic_options_1.Monotonicity.WEAKLY_DECREASING: { return value <= 0; } case array_monotonic_options_1.Monotonicity.STRICTLY_DECREASING: { return value < 0; } /* istanbul ignore next */ default: { throw new TypeError('Unexpected monotonicity value'); } } } function compareItems(a, b, options) { if ('projection' in options) { return checkMonotonicity(options.projection(b) - options.projection(a), options.monotonicity); } if ('comparator' in options) { return checkMonotonicity(options.comparator(b, a), options.monotonicity); } return checkMonotonicity(Number(b) - Number(a), options.monotonicity); } const allowedValues = new Set(Object.values(array_monotonic_options_1.Monotonicity)); /** * @category Predicates * @param value The value to validate. * @param options Additional options (see {@link ArrayMonotonic}). * @typeParam T The type of the array elements. */ function arrayMonotonic(value, options) { if (!allowedValues.has(options.monotonicity)) { const allowedValuesString = [...allowedValues].map(allowed => `"${allowed}"`).join(', '); throw new TypeError(`Unknown monotonicity type "${options.monotonicity}" (expected one of ${allowedValuesString})`); } return (Array.isArray(value) && value.every((item, index) => index === 0 || compareItems(value[index - 1], item, options))); }