Separated formatting

This commit is contained in:
2026-07-15 12:03:30 +02:00
parent d2cc33d517
commit f5d3055174
3 changed files with 157 additions and 87 deletions
+120
View File
@@ -0,0 +1,120 @@
use crate::types::{ActivePosition, WatchListItem};
pub trait Formatted {
fn get_formatted(&self) -> Vec<String>;
}
impl Formatted for WatchListItem {
fn get_formatted(&self) -> Vec<String> {
vec![
format!("\x1b[35m{}\x1b[0m", self.symbol.to_string()),
format_f64(self.price),
format!(
"{} {}",
if self.trend.is_sign_positive() {
"\x1b[32m▲\x1b[0m"
} else {
"\x1b[31m▼\x1b[0m"
},
format_f64(self.trend.abs())
),
]
}
}
impl Formatted for ActivePosition {
fn get_formatted(&self) -> Vec<String> {
vec![
format!("\x1b[35m{}\x1b[0m", self.symbol.to_string()),
format_f64(self.amount),
format!(
"{} {}",
if self.profit.is_sign_positive() {
"\x1b[32m▲\x1b[0m"
} else {
"\x1b[31m▼\x1b[0m"
},
format_f64(self.profit.abs())
),
]
}
}
impl<T: Formatted> Formatted for Vec<T> {
fn get_formatted(&self) -> Vec<String> {
let mut output = Vec::new();
let rows: Vec<Vec<String>> = self.iter().map(|v| v.get_formatted()).collect();
if rows.is_empty() {
return output;
}
let column_count = rows.iter().map(|r| r.len()).max().unwrap_or(0);
let mut widths = vec![0; column_count];
for row in &rows {
for (i, col) in row.iter().enumerate() {
widths[i] = widths[i].max(col.len());
}
}
for row in rows {
let mut row_out = String::new();
for (col_idx, col) in row.iter().enumerate() {
let width = widths[col_idx];
row_out.push_str(&format!("{:>width$}", col, width = width));
if col_idx + 1 != row.len() {
row_out.push_str(" ");
}
}
output.push(row_out);
}
output
}
}
pub fn apply_padding(mut items: Vec<String>) -> Vec<String> {
for item in &mut items {
item.insert(0, ' ');
}
items
}
pub fn format_f64(value: f64) -> String {
let val = value.to_string();
let parts: Vec<&str> = val.split('.').collect();
let int = parts[0].to_string();
let negative = int.starts_with('-');
let start = if negative { 1 } else { 0 };
let mut result = String::new();
for (i, c) in int[start..].chars().rev().enumerate() {
if i > 0 && i % 3 == 0 {
result.push(',');
}
result.push(c);
}
let mut formatted: String = result.chars().rev().collect();
if negative {
formatted.insert(0, '-');
}
if parts.len() > 1 {
formatted.push('.');
formatted.push_str(parts[1]);
}
formatted
}