Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Оригинальный код
- //
- pub fn format_duration(duration: Duration) -> String {
- let total_seconds = duration.as_secs();
- let hours = total_seconds / 3600;
- let minutes = (total_seconds % 3600) / 60;
- let seconds = total_seconds % 60;
- let hours_label = match hours {
- 1 => "hour",
- _ => "hours"
- };
- let minutes_label = match minutes {
- 1 => "minute",
- _ => "minutes"
- };
- let seconds_label = match seconds {
- 1 => "second",
- _ => "seconds"
- };
- let mut text = String::new();
- if hours > 0 {
- push_value_and_label(&mut text, hours, hours_label);
- }
- if minutes > 0 {
- if !text.is_empty() {
- text.push(' ');
- }
- push_value_and_label(&mut text, minutes, minutes_label);
- }
- if !text.is_empty() {
- text.push(' ');
- }
- push_value_and_label(&mut text, seconds, seconds_label);
- text
- }
- fn push_value_and_label(text: &mut String, value: u64, label: &str) {
- write!(text, "{} {}", value, label).unwrap();
- }
- //
- // Предложенный альтернативный вариант
- //
- fn summon_satan(seconds: u64) -> String {
- let labels = vec!["hour", "minute", "second"];
- let parts = vec![seconds / 3600, (seconds % 3600) / 60, seconds % 60];
- let index = parts.iter().position(|&p| p != 0).unwrap_or(2);
- let parts_n_labels = parts[index..].iter().zip(labels[index..].iter());
- let strs = parts_n_labels.map(|(&part, &label)| format!("{} {}{}", part, label, if part == 1 { "" } else { "s" }));
- return strs.collect::<Vec<String>>().join(" ");
- }
- // Источники:
- // https://theiced.livejournal.com/499970.html
- // https://theiced.livejournal.com/500541.html
Advertisement
Add Comment
Please, Sign In to add comment