From d4c4b207db8c625f6163423c1f4c8a58a934c0b0 Mon Sep 17 00:00:00 2001 From: Florian Mros Date: Fri, 8 Nov 2024 16:29:38 +0100 Subject: [PATCH] feat(combinator): displayExpression with prefix notation --- src/combinator.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/combinator.cpp b/src/combinator.cpp index c0aa5d6..348a663 100644 --- a/src/combinator.cpp +++ b/src/combinator.cpp @@ -26,6 +26,7 @@ #include #include +#include using Log = metricq::logger::nitro::Log; @@ -49,6 +50,47 @@ Combinator::~Combinator() { } +std::string displayExpression(const nlohmann::json& expression) { + static const std::unordered_set validOperators = { "+", "-", "*", "/" }; + + // Check if the expression is a number and return it as a string + if (expression.is_number()) { + double value = expression.get(); + return (value == static_cast(value)) ? std::to_string(static_cast(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(); + if (operand.is_number()) return std::to_string(operand.get()); + 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(); + } + + return "Unknown expression format"; +} + void Combinator::on_transformer_config(const metricq::json& config) { input_metrics.clear(); @@ -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();