Sha256: 26ced5160823445c46d7f8d0e6fbb035ebc73c9812913b50f417ad521842a330

Contents?: true

Size: 1.13 KB

Versions: 289

Compression:

Stored size: 1.13 KB

Contents

pub trait Luhn {
    fn valid_luhn(&self) -> bool;
}

impl Luhn for String {
    fn valid_luhn(&self) -> bool {
        if self.chars().any(|c| c.is_alphabetic()) || self.chars().count() == 1 {
            return false;
        }

        self.chars()
            .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<'a> Luhn for &'a str {
    fn valid_luhn(&self) -> bool {
        String::from(*self).valid_luhn()
    }
}

impl Luhn for u8 {
    fn valid_luhn(&self) -> bool {
        self.to_string().valid_luhn()
    }
}

impl Luhn for u16 {
    fn valid_luhn(&self) -> bool {
        self.to_string().valid_luhn()
    }
}

impl Luhn for u32 {
    fn valid_luhn(&self) -> bool {
        self.to_string().valid_luhn()
    }
}

impl Luhn for u64 {
    fn valid_luhn(&self) -> bool {
        self.to_string().valid_luhn()
    }
}

impl Luhn for usize {
    fn valid_luhn(&self) -> bool {
        self.to_string().valid_luhn()
    }
}

Version data entries

289 entries across 289 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.179 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.178 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.177 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.176 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.175 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.174 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.173 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.172 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.171 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.170 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.169 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.167 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.166 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.165 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.164 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.163 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.162 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.161 tracks/rust/exercises/luhn-trait/example.rs
trackler-2.2.1.160 tracks/rust/exercises/luhn-trait/example.rs