Slight refactor of calculate_dice_amount. Lazy error handling.
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
Use unwrap_or_else instead of unwrap_or to prevent unnecessary error string creation. Also some changes to make the code a bit more readable.
This commit is contained in:
parent
7512ca0694
commit
f5a8e16ce0
17
src/dice.rs
17
src/dice.rs
|
@ -6,26 +6,27 @@ use crate::parser::Amount;
|
||||||
use crate::parser::Element as NewElement;
|
use crate::parser::Element as NewElement;
|
||||||
use futures::stream::{self, StreamExt, TryStreamExt};
|
use futures::stream::{self, StreamExt, TryStreamExt};
|
||||||
|
|
||||||
//New hotness
|
/// Calculate the amount of dice to roll by consulting the database
|
||||||
|
/// and replacing variables with corresponding amounts. Errors out if
|
||||||
|
/// it cannot find a variable defined, or if the database errors.
|
||||||
pub async fn calculate_dice_amount(amounts: &[Amount], ctx: &Context<'_>) -> Result<i32, BotError> {
|
pub async fn calculate_dice_amount(amounts: &[Amount], ctx: &Context<'_>) -> Result<i32, BotError> {
|
||||||
let stream = stream::iter(amounts);
|
let stream = stream::iter(amounts);
|
||||||
let key = UserAndRoom(&ctx.username, ctx.room.id.as_str());
|
let key = UserAndRoom(&ctx.username, ctx.room.id.as_str());
|
||||||
let variables = &ctx.db.variables.get_user_variables(&key)?;
|
let variables = &ctx.db.variables.get_user_variables(&key)?;
|
||||||
|
|
||||||
use DiceRollingError::VariableNotFound;
|
use DiceRollingError::VariableNotFound;
|
||||||
let dice_amount: Result<i32, BotError> = stream
|
let dice_amount: i32 = stream
|
||||||
.then(|amount| async move {
|
.then(|amount| async move {
|
||||||
match &amount.element {
|
match &amount.element {
|
||||||
NewElement::Number(num_dice) => Ok(*num_dice * amount.operator.mult()),
|
NewElement::Number(num_dice) => Ok(num_dice * amount.operator.mult()),
|
||||||
NewElement::Variable(variable) => variables
|
NewElement::Variable(variable) => variables
|
||||||
.get(variable)
|
.get(variable)
|
||||||
.ok_or(VariableNotFound(variable.clone().to_string()))
|
.ok_or_else(|| VariableNotFound(variable.clone()))
|
||||||
.map(|i| *i)
|
.map(|i| *i),
|
||||||
.map_err(|e| e.into()),
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.try_fold(0, |total, num_dice| async move { Ok(total + num_dice) })
|
.try_fold(0, |total, num_dice| async move { Ok(total + num_dice) })
|
||||||
.await;
|
.await?;
|
||||||
|
|
||||||
dice_amount
|
Ok(dice_amount)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue