Skip to content

Commit

Permalink
Loop once in computeMostCommonTarget
Browse files Browse the repository at this point in the history
  • Loading branch information
dapplion committed Feb 28, 2022
1 parent 07fbc13 commit 1e381fd
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions packages/lodestar/src/sync/range/utils/chainTarget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,24 @@ export type ChainTarget = {
};

export function computeMostCommonTarget(targets: ChainTarget[]): ChainTarget | null {
const targetsById = new Map<string, ChainTarget>();
if (targets.length === 0) {
return null;
}

const countById = new Map<string, number>();

let mostCommonTarget = targets[0];
let mostCommonCount = 0;

for (const target of targets) {
const targetId = `${target.slot}-${toHexString(target.root)}`;
targetsById.set(targetId, target);
countById.set(targetId, 1 + (countById.get(targetId) ?? 0));
}

let mostCommon: {count: number; targetId: string} | null = null;
for (const [targetId, count] of countById.entries()) {
if (!mostCommon || count > mostCommon.count) {
mostCommon = {count, targetId};
const count = 1 + (countById.get(targetId) ?? 0);
countById.set(targetId, count);
if (count > mostCommonCount) {
mostCommonCount = count;
mostCommonTarget = target;
}
}

return mostCommon && (targetsById.get(mostCommon.targetId) ?? null);
return mostCommonTarget;
}

0 comments on commit 1e381fd

Please sign in to comment.