Refactored to use max_by

This commit is contained in:
pawanjay176 2019-03-13 14:31:40 +05:30
parent 2b7aa269c3
commit 181aeb3d71

View File

@ -8,6 +8,7 @@ use db::{
}; };
use log::{debug, trace}; use log::{debug, trace};
use std::collections::HashMap; use std::collections::HashMap;
use std::cmp::Ordering;
use std::sync::Arc; use std::sync::Arc;
use types::{ use types::{
readers::BeaconBlockReader, validator_registry::get_active_validator_indices, BeaconBlock, readers::BeaconBlockReader, validator_registry::get_active_validator_indices, BeaconBlock,
@ -199,19 +200,19 @@ where
if votes.is_empty() { if votes.is_empty() {
return None; return None;
} }
let mut best_child: Hash256 = Hash256::from(0);
let mut max_votes: u64 = 0; // Iterate through hashmap to get child with maximum votes
for (&candidate, &votes) in votes.iter() { let best_child = votes.iter().max_by(|(child1,v1), (child2, v2)| {
// Choose the smaller hash to break ties deterministically let mut result = v1.cmp(v2);
if votes == max_votes && candidate < best_child { // If votes are equal, choose smaller hash to break ties deterministically
best_child = candidate; if result == Ordering::Equal {
// Reverse so that max_by chooses smaller hash
result = child1.cmp(child2).reverse();
} }
if votes > max_votes { result
max_votes = votes; });
best_child = candidate;
} Some(*best_child.unwrap().0)
}
Some(best_child)
} }
} }