CodeSOD: A Bit Overcomplicated
Lets say you have a 64-bit integer. You want the first 42-bits. Now, if your language has a bitshift operator, you'd be tempted to do something like largeNumber >> 22.
But what if your language also has all sorts of advanced stream processing and map functions? It'd be a shame to not use those. Tarah's shop uses Rust, and thus they do have all those exciting advanced stream processing. Her co-worker decided they just needed to be used:
let binary = format!("{:b}", snowflake);let in_binary: u64 = binary[..42] .to_string() .chars() .rev() .enumerate() .map(|(idx, digit)| { (u64::from_str_radix(&digit.to_string(), 2).unwrap()) * ((2_u64).pow(idx as u32)) }) .sum();
This starts by taking a number, and converting it into a string containing the binary representation. Then we chop off the first 42 characters of that string, break them into characters, reverse the stream, enumerate it, and then apply a map where we parse each character back into a number (which will be 0 or 1), and then multiply it by two raised to the power of the index we're on. sum all that up, and we've got the first 42 bits of a 64-bit number.
And sure, snowflake >> 22 would be shorter, clearer, and far more efficient, but it wouldn't let you show off all the cool language features you have at your disposal, and isn't that what's really important?
[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!