Skip to content

Commit

Permalink
feat(combinator): displayExpression with prefix notation
Browse files Browse the repository at this point in the history
  • Loading branch information
floork committed Nov 8, 2024
1 parent eeb0c42 commit d4c4b20
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/combinator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include <fmt/format.h>

#include <numeric>
#include <unordered_set>

using Log = metricq::logger::nitro::Log;

Expand All @@ -49,6 +50,47 @@ Combinator::~Combinator()
{
}

std::string displayExpression(const nlohmann::json& expression) {
static const std::unordered_set<std::string> validOperators = { "+", "-", "*", "/" };

// Check if the expression is a number and return it as a string
if (expression.is_number()) {
double value = expression.get<double>();
return (value == static_cast<int>(value)) ? std::to_string(static_cast<int>(value)) : std::to_string(value);
}

if (expression.is_object() && expression.contains("operation")) {
std::string operation = expression.value("operation", "");

// Validate if the operation is supported
if (validOperators.find(operation) == validOperators.end()) {
return operation;
}

// Helper lambda to process operands
auto processOperand = [&](const std::string& key) -> std::string {
if (expression.contains(key)) {
const auto& operand = expression[key];
if (operand.is_string()) return operand.get<std::string>();
if (operand.is_number()) return std::to_string(operand.get<int>());
return displayExpression(operand);
}
return "";
};

std::string leftStr = processOperand("left");
std::string rightStr = processOperand("right");
return operation + (leftStr.empty() ? "" : " " + leftStr) + (rightStr.empty() ? "" : " " + rightStr);
}

// If the expression is a string, return it directly
if (expression.is_string()) {
return expression.get<std::string>();
}

return "Unknown expression format";
}

void Combinator::on_transformer_config(const metricq::json& config)
{
input_metrics.clear();
Expand Down Expand Up @@ -93,6 +135,8 @@ void Combinator::on_transformer_config(const metricq::json& config)
// Register the combined metric as a new source metric
auto& metric = (*this)[combined_name];

metric.metadata["displayExpression"] = displayExpression(combined_expression);

if (combined_config.count("chunk_size"))
{
auto chunk_size = combined_config["chunk_size"].get<int>();
Expand Down

0 comments on commit d4c4b20

Please sign in to comment.