Sha256: e4de21094069b4e3e327c3adb27df8c90c47a538e1bca8a4f89583484b404055

Contents?: true

Size: 1.24 KB

Versions: 288

Compression:

Stored size: 1.24 KB

Contents

pub struct Luhn {
    digits: Vec<char>,
}

impl Luhn {
    pub fn is_valid(&self) -> bool {
        if self.digits.iter().any(|c| c.is_alphabetic()) || self.digits.iter().count() == 1 {
            return false;
        }

        self.digits
            .iter()
            .filter_map(|c| c.to_digit(10))
            .rev()
            .enumerate()
            .map(|(index, digit)| if index % 2 == 0 { digit } else { digit * 2 })
            .map(|digit| if digit > 9 { digit - 9 } else { digit })
            .sum::<u32>() % 10 == 0
    }
}

impl From<String> for Luhn {
    fn from(s: String) -> Self {
        Luhn { digits: s.chars().collect() }
    }
}

impl<'a> From<&'a str> for Luhn {
    fn from(s: &'a str) -> Self {
        Luhn::from(String::from(s))
    }
}

impl From<u8> for Luhn {
    fn from(s: u8) -> Self {
        Luhn::from(s.to_string())
    }
}

impl From<u16> for Luhn {
    fn from(s: u16) -> Self {
        Luhn::from(s.to_string())
    }
}

impl From<u32> for Luhn {
    fn from(s: u32) -> Self {
        Luhn::from(s.to_string())
    }
}

impl From<u64> for Luhn {
    fn from(s: u64) -> Self {
        Luhn::from(s.to_string())
    }
}

impl From<usize> for Luhn {
    fn from(s: usize) -> Self {
        Luhn::from(s.to_string())
    }
}

Version data entries

288 entries across 288 versions & 1 rubygems

Version Path
trackler-2.2.1.158 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.157 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.156 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.155 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.154 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.153 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.152 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.151 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.150 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.149 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.148 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.147 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.146 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.145 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.144 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.143 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.142 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.141 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.140 tracks/rust/exercises/luhn-from/example.rs
trackler-2.2.1.139 tracks/rust/exercises/luhn-from/example.rs