UNPKG

@lucaspaganini/value-objects

Version:

TypeScript first validation and class creation library

85 lines 3.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VOInteger = void 0; var utils_1 = require("../utils"); var errors_1 = require("./errors"); /** * Function to create an integer number value object constructor. * * > NOTE: If you want to accept floating point numbers and convert them to * integers, you can use {@link VOFloat} and set the precision option to 0. * * @param options Customizations for the returned class constructor * @return Class constructor that accepts a (integer) number for instantiation * and returns that number when {@link VOIntegerInstance.valueOf} is called. * * @example * ```typescript * class MyInteger extends VOInteger() {} * * const int1 = new MyInteger(5); // OK * int1.valueOf(); // 5 * * const int2 = new MyInteger(5.0); // OK * int2.valueOf(); // 5 * * const int3 = new MyInteger(5.5); // Runtime error: Not an integer * ``` * * @example * ```typescript * class NaturalNumber extends VOInteger({ min: 0 }) {} // OK * new NaturalNumber(0); // OK * new NaturalNumber(1000000); // Ok * new NaturalNumber(-1); // Runtime error: Too small * new NaturalNumber(1.5); // Runtime error: Not an integer * ``` * * @example * ```typescript * class MyFloatRangeInteger extends VOInteger({ min: -100.5, max: 100.5 }) {} // OK * new MyFloatRangeInteger(-100); // OK * new MyFloatRangeInteger(100); // Ok * new MyFloatRangeInteger(-101); // Runtime error: Too small * new MyFloatRangeInteger(101); // Runtime error: Too big * ``` * * @example * ```typescript * class MyInvalidInteger extends VOInteger({ min: 100, max: -100 }) {} // Runtime error: Invalid logic (options.min should not be bigger than options.max) * ``` */ var VOInteger = function (options) { if (options === void 0) { options = {}; } if (utils_1.isDefined(options.min)) { if (typeof options.min !== 'number') throw new errors_1.RawTypeError('number', typeof options.min, 'options.min'); } if (utils_1.isDefined(options.max)) { if (typeof options.max !== 'number') throw new errors_1.RawTypeError('number', typeof options.max, 'options.max'); } if (utils_1.isDefined(options.min) && utils_1.isDefined(options.max)) { if (options.min > options.max) throw new errors_1.LogicError('options.min should not be bigger than options.max'); } return /** @class */ (function () { function class_1(raw) { if (typeof raw !== 'number') throw new errors_1.RawTypeError('number', typeof raw, 'raw'); if (utils_1.isDefined(options.min) && raw < options.min) throw new errors_1.MinSizeError(options.min, raw); if (utils_1.isDefined(options.max) && raw > options.max) throw new errors_1.MaxSizeError(options.max, raw); if (!Number.isInteger(raw)) throw new errors_1.NotIntegerError(raw); this._value = raw; } class_1.prototype.valueOf = function () { return this._value; }; return class_1; }()); }; exports.VOInteger = VOInteger; //# sourceMappingURL=integer.js.map