[Base]retrieve unit text

Co-authored-by: Chris Hennes <chennes@pioneerlibrarysystem.org>
This commit is contained in:
wandererfan
2025-10-19 15:56:47 -04:00
committed by Chris Hennes
parent a431ccc156
commit c9fffa6789
4 changed files with 40 additions and 0 deletions

View File

@@ -35,6 +35,8 @@
#include "Exception.h"
#include "Quantity.h"
#include "Console.h"
using Base::UnitsSchema;
using Base::UnitsSchemaSpec;
@@ -143,3 +145,34 @@ int UnitsSchema::getNum() const
{
return static_cast<int>(spec.num);
}
//! return the unit text for this quantity in this schema. ex 10 mm => "mm"
//! a more general approach than getBasicLengthUnit.
//! TODO: some common code here with translate()
std::string UnitsSchema::getUnitText(const Base::Quantity& quant) const
{
std::string typeString = quant.getUnit().getTypeString(); // "Area", "Mass", ...
const auto value = quant.getValue();
// TODO: some common code here with translate()
if (!spec.translationSpecs.contains(typeString)) {
Base::Console().log("Schema %s has no entry for %s\n",
getName().c_str(),
typeString.c_str());
return {};
}
auto unitSpecs = spec.translationSpecs.at(typeString);
auto isSuitable = [&](const UnitTranslationSpec& row) {
return row.threshold > value || row.threshold == 0;
};
const auto unitSpec = std::ranges::find_if(unitSpecs, isSuitable);
if (unitSpec == unitSpecs.end()) {
throw RuntimeError("Suitable threshold not found (2). Schema: " + spec.name
+ " value: " + std::to_string(value));
}
return unitSpec->unitString;
}