model-layer
Version:
111 lines • 3.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NumberType = void 0;
const Type_1 = require("./Type");
const utils_1 = require("../utils");
const errors_1 = require("../errors");
class NumberType extends Type_1.Type {
constructor({ nullAsZero = false, zeroAsNull = false, ceil, round, floor, ...otherParams }) {
super(otherParams);
this.nullAsZero = nullAsZero;
this.zeroAsNull = zeroAsNull;
if (nullAsZero && zeroAsNull) {
throw new errors_1.ConflictNullAndZeroParameterError({});
}
if (ceil != null) {
if (utils_1.isNaN(+ceil)) {
throw new errors_1.InvalidRoundError({
roundType: "ceil",
invalidValue: utils_1.invalidValuesAsString(ceil)
});
}
ceil = +ceil;
}
this.ceil = ceil;
if (round != null) {
if (utils_1.isNaN(+round)) {
throw new errors_1.InvalidRoundError({
roundType: "round",
invalidValue: utils_1.invalidValuesAsString(round)
});
}
if (ceil != null) {
throw new errors_1.ConflictFloorCeilRoundError({});
}
round = +round;
}
this.round = round;
if (floor != null) {
if (utils_1.isNaN(+floor)) {
throw new errors_1.InvalidRoundError({
roundType: "floor",
invalidValue: utils_1.invalidValuesAsString(floor)
});
}
if (ceil != null) {
throw new errors_1.ConflictFloorCeilRoundError({});
}
if (round != null) {
throw new errors_1.ConflictFloorCeilRoundError({});
}
floor = +floor;
}
this.floor = floor;
}
prepare(originalValue, key) {
if (originalValue == null) {
if (this.nullAsZero) {
return 0;
}
return null;
}
let value = +originalValue;
if (utils_1.isNaN(value) ||
typeof originalValue === "boolean" ||
originalValue instanceof RegExp ||
originalValue instanceof Date ||
Array.isArray(originalValue) ||
// infinity
value === 1 / 0 ||
value === -1 / 0) {
const valueAsString = utils_1.invalidValuesAsString(originalValue);
throw new errors_1.InvalidNumberError({
key,
invalidValue: valueAsString
});
}
if (this.round != null) {
const desc = Math.pow(10, this.round);
value = Math.round(value *
desc) / desc;
}
else if (this.floor != null) {
const desc = Math.pow(10, this.floor);
value = Math.floor(value *
desc) / desc;
}
else if (this.ceil != null) {
// 1.12 * 100 == 112.00000000000001
let valueStr = value.toString();
let commaPosition = valueStr.indexOf(".");
if (commaPosition !== -1) {
commaPosition += this.ceil;
valueStr = valueStr.replace(".", "");
valueStr = (valueStr.slice(0, commaPosition) +
"." +
valueStr.slice(commaPosition));
value = +valueStr;
const desc = Math.pow(10, this.ceil);
value = Math.ceil(value) / desc;
}
}
if (this.zeroAsNull) {
if (value === 0) {
value = null;
}
}
return value;
}
}
exports.NumberType = NumberType;
//# sourceMappingURL=NumberType.js.map