Skip to content

Conversation

@AliAlimohammadi
Copy link
Contributor

Description

This PR adds a new module for converting between different time units (seconds, minutes, hours, days, weeks, months, and years).

Features Added

  • convert_time: Convert time values between any two supported units
  • TimeUnit enum for type-safe time unit representation
  • Case-insensitive unit name parsing
  • Custom error types with descriptive messages
  • Comprehensive test coverage (13 unit tests)

Type of Change

  • ✅ New algorithm/data structure
  • ✅ Documentation
  • ✅ Tests

Testing

All tests pass:

cargo test time_units::tests

Results:

  • 13 unit tests passed
  • Test coverage includes:
    • Basic conversions (seconds ↔ hours, minutes ↔ seconds, etc.)
    • Case-insensitive input handling
    • Multi-unit conversions (weeks → days, days → months, months → years)
    • Input validation (negative values, invalid units)
    • Edge cases (zero values, same-unit conversions)
    • Precision (results rounded to 3 decimal places)

Algorithm Complexity

  • Time Complexity: $O(1)$ - constant time operations (direct multiplication/division)
  • Space Complexity: $O(1)$ - fixed size enum and primitive types

Implementation Details

Conversion Algorithm

  • Uses seconds as the base unit for all conversions
  • Two-step process:
    1. Convert input value from source unit → seconds
    2. Convert seconds → target unit
  • Results rounded to 3 decimal places for precision

Time Unit Values

All conversions use these standardized values:

  • Seconds: 1.0 (base unit)
  • Minutes: 60.0
  • Hours: 3,600.0
  • Days: 86,400.0
  • Weeks: 604,800.0
  • Months: 2,629,800.0 (approximate - based on 30.44 day average month)
  • Years: 31,557,600.0 (approximate - based on 365.25 day average year)

Enum-Based Design

  • Uses TimeUnit enum instead of string dictionaries for type safety
  • Implements Copy trait for efficient passing
  • Private helper methods for conversion logic

Case Handling

  • All unit names are case-insensitive
  • TimeUnit::from_str() normalizes input with .to_lowercase()
  • Accepts: "HOURS", "Hours", "hours", etc.

Error Handling

Returns Result<f64, String> with descriptive error messages:

  • Negative values: "'time_value' must be a non-negative number."
  • Invalid numbers: Catches NaN and Infinity values
  • Unknown units: "Invalid unit {unit} is not in seconds, minutes, hours, days, weeks, months, years."

Example error handling:

match convert_time(-5.0, "seconds", "hours") {
    Ok(value) => println!("{}", value),
    Err(e) => eprintln!("Error: {}", e),
}

References

Checklist

  • ✅ Code follows Rust idioms and best practices
  • ✅ Self-documenting code with comprehensive doc comments
  • ✅ All functions have doc comments
  • ✅ Tests cover normal cases, edge cases, and error cases
  • ✅ Code compiles without warnings (clippy clean)
  • ✅ All tests pass
  • ✅ Proper use of type-safe enum (TimeUnit)
  • ✅ Input validation in main function
  • ✅ Module properly integrated into src/conversions/mod.rs

Example Usage

use conversions::time_units::convert_time;

// Basic conversion
let hours = convert_time(3600.0, "seconds", "hours").unwrap();
assert_eq!(hours, 1.0);

// Case-insensitive
let result = convert_time(1.0, "DaYs", "hours").unwrap();
assert_eq!(result, 24.0);

// Multi-step conversions
let weeks = convert_time(2.0, "WEEKS", "days").unwrap();
assert_eq!(weeks, 14.0);

// Fractional values
let minutes = convert_time(0.5, "hours", "MINUTES").unwrap();
assert_eq!(minutes, 30.0);

// Error handling
match convert_time(-3600.0, "seconds", "hours") {
    Ok(_) => println!("Success"),
    Err(e) => println!("Error: {}", e), // "'time_value' must be a non-negative number."
}

// Invalid units
match convert_time(1.0, "parsecs", "fortnights") {
    Ok(_) => println!("Success"),
    Err(e) => println!("Error: {}", e), // "Invalid unit parsecs is not in..."
}

Additional Notes

  • Month and year values are approximate - months vary from 28-31 days, years can be 365 or 366 days
    • Month = 30.44 days (average)
    • Year = 365.25 days (accounting for leap years)
  • Results are rounded to 3 decimal places to maintain precision while avoiding floating-point artifacts
  • All unit names are case-insensitive for user convenience
  • Zero values and same-unit conversions are handled correctly
  • The module is fully self-contained with no external dependencies beyond std

@AliAlimohammadi
Copy link
Contributor Author

@siriak, this is ready to be merged.

@codecov-commenter
Copy link

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.97%. Comparing base (47ea8bd) to head (8114f0e).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #996   +/-   ##
=======================================
  Coverage   95.96%   95.97%           
=======================================
  Files         364      365    +1     
  Lines       24810    24888   +78     
=======================================
+ Hits        23810    23887   +77     
- Misses       1000     1001    +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@siriak siriak merged commit 324ab51 into TheAlgorithms:master Jan 16, 2026
7 checks passed
@AliAlimohammadi AliAlimohammadi deleted the add-time-conversion branch January 16, 2026 18:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants