@k8ts/instruments
Version:
A collection of utilities and core components for k8ts.
59 lines • 1.88 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnitParser = exports.UnitValue = void 0;
const parjs_1 = require("parjs");
const combinators_1 = require("parjs/combinators");
const error_1 = require("../error");
const pUnit = (0, parjs_1.letter)().pipe((0, combinators_1.many1)(2), (0, combinators_1.stringify)());
const pValueUnit = (0, parjs_1.int)().pipe((0, combinators_1.then)(pUnit), (0, combinators_1.map)(arr => {
const [value, unit] = arr;
return { value, unit };
}));
class UnitValue {
unit;
value;
type;
constructor(unit, value, type) {
this.unit = unit;
this.value = value;
this.type = type;
}
get str() {
return `${this.value}${this.unit}`;
}
toString() {
return this.str;
}
}
exports.UnitValue = UnitValue;
class UnitParser {
unitType;
_units;
parser;
constructor(unitType, _units) {
this.unitType = unitType;
this._units = _units;
this.parser = pValueUnit.pipe((0, combinators_1.map)(({ value, unit }) => {
const gotType = this._units.has(unit);
if (!gotType) {
throw new error_1.InstrumentsError(`Unit ${unit} is not a valid unit of type ${this.unitType}`);
}
return new UnitValue(unit, value, this.unitType);
}));
}
parse = (input) => {
const pUnitValue = this.parser;
const result = pUnitValue.parse(input);
if (result.kind !== "OK") {
throw new error_1.InstrumentsError(`Failed to parse ${this.unitType}`, {
more: result.trace.toString()
});
}
return result.value;
};
static make(unitType, units) {
return new UnitParser(unitType, units);
}
}
exports.UnitParser = UnitParser;
//# sourceMappingURL=unit-parser.js.map