Skip to content

Commit 4992901

Browse files
committed
Optimize completed logic
1 parent 875cf05 commit 4992901

1 file changed

Lines changed: 12 additions & 9 deletions

File tree

lib/fast-tracker.ts

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -328,40 +328,43 @@ class Swarm {
328328
public completedCount = 0;
329329

330330
private _peers: PeerContext[] = [];
331-
private isPeerCompleted: boolean[] = [];
331+
private completedPeers?: Set<string>;
332332

333333
constructor(readonly infoHash: string) {}
334334

335335
public addPeer(peer: PeerContext, completed: boolean) {
336336
this._peers.push(peer);
337-
this.isPeerCompleted.push(completed);
338337
if (completed) {
338+
if (this.completedPeers === undefined) {
339+
this.completedPeers = new Set();
340+
}
341+
this.completedPeers.add(peer.id!);
339342
this.completedCount++;
340343
}
341344
}
342345

343346
public removePeer(peer: PeerContext) {
344347
const index = this._peers.indexOf(peer);
345348

346-
if (this.isPeerCompleted[index]) {
349+
if ((this.completedPeers !== undefined) && this.completedPeers.delete(peer.id!)) {
347350
this.completedCount--;
348351
}
349352

350-
// Delete peerId from arrays without calling splice
353+
// Delete peerId from array without calling splice
351354
const last = this._peers.pop()!;
352-
const lastIsCompleted = this.isPeerCompleted.pop()!;
353355
if (index < this._peers.length) {
354356
this._peers[index] = last;
355-
this.isPeerCompleted[index] = lastIsCompleted;
356357
}
357358
}
358359

359360
public setCompleted(peer: PeerContext) {
360-
const index = this._peers.indexOf(peer);
361+
if (this.completedPeers === undefined) {
362+
this.completedPeers = new Set();
363+
}
361364

362-
if (!this.isPeerCompleted[index]) {
365+
if (!this.completedPeers.has(peer.id!)) {
366+
this.completedPeers.add(peer.id!);
363367
this.completedCount++;
364-
this.isPeerCompleted[index] = true;
365368
}
366369
}
367370

0 commit comments

Comments
 (0)