Skip to content

Commit

Permalink
polish: code review
Browse files Browse the repository at this point in the history
  • Loading branch information
flyingtof committed Sep 5, 2024
1 parent e83e086 commit a2b9f5d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 25 deletions.
9 changes: 5 additions & 4 deletions apps/fxc-front/src/app/components/2d/path-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export class PathElement extends connect(store)(LitElement) {
private faiSectors?: FaiSectors;
private plannerElement?: PlannerElement;
private scorer?: Scorer;
private scoreInProgress?: HTMLIonToastElement;
private toastScoring?: HTMLIonToastElement;

stateChanged(state: RootState): void {
this.currentTrack = currentTrack(state);
Expand Down Expand Up @@ -269,6 +269,7 @@ export class PathElement extends connect(store)(LitElement) {
kms = scoringResult.lengthKm.toFixed(1);
circuit = CIRCUIT_SHORT_NAME[scoringResult.circuit];
if (scoringResult.circuit === CircuitType.OpenDistance) {
scoringResult.turnpoints.length
circuit += scoringResult.solutionIndices.length - 2;
}
window.parent.postMessage(
Expand Down Expand Up @@ -353,12 +354,12 @@ export class PathElement extends connect(store)(LitElement) {
}

// TODO: dialog if too long
this.scoreInProgress = await toastController.create({
this.toastScoring = await toastController.create({
message: 'Scoring in progress',
position: 'middle',
duration: 30000,
});
await this.scoreInProgress.present();
await this.toastScoring.present();

const track = this.currentTrack;
const points = track.lat.map((lat, index) => ({
Expand All @@ -369,7 +370,7 @@ export class PathElement extends connect(store)(LitElement) {
}));
this.getScorer().score(points, this.league, async (result) => {
this.handleScoringResult(result);
await this.scoreInProgress?.dismiss();
await this.toastScoring?.dismiss();
});
});
}
Expand Down
2 changes: 1 addition & 1 deletion apps/fxc-front/src/app/components/2d/planner-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export class PlannerElement extends connect(store)(LitElement) {
</div>
<div class="collapsible">
<div>Points = ${this.getMultiplier()}</div>
<div class="large">${this.score?.score.toFixed(1)}</div>
<div class="large">${this.score ? this.score.score.toFixed(1) : '-'}</div>
</div>
<div class="collapsible">
<div>Total distance</div>
Expand Down
37 changes: 17 additions & 20 deletions apps/fxc-front/src/app/logic/score/scorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,21 @@ export type ScoringResultHandler = (result: ScoringResult) => void;
export class Scorer {
private scoringWorker?: Worker;
private currentScoringRequestId = 0;
/**
* Associate the result handler of every scoring request with the scoring request identifier.
* The scoring request identifier is a sequence number computed by incrementation of `currentScoringRequestId` field.
* This identifier is sent to the worker (`id` field of the message) and returned by the worker in the response
* message (`data.id` field).
* The handler is retrieved and invoked when the worker response is received.
*/
private handlers: Map<number, ScoringResultHandler> = new Map();

/**
* Scores a track
*
* `handleScoringResult` function is invoked in a
* worker context which means that 'this' keyword is a reference to the worker itself.
* If a function body uses 'this' keyword and is sent to the constructor as a reference, it will not work.
* In this case, the function should be wrapped in an arrow function (see example bellow).<br/>
* `handleScoringResult` function is invoked in a worker context which means that 'this' keyword is a reference
* to the worker itself. If a function body uses 'this' keyword and is sent to the constructor as a reference,
* it will not work. In this case, the function should be wrapped in an arrow function (see example bellow).<br/>
*
* E.g:
* ```
Expand Down Expand Up @@ -46,20 +52,20 @@ export class Scorer {
public score(track: LatLonAltTime[], league: LeagueCode, handleScoringResult: ScoringResultHandler): number {
// lazy creation of the worker
this.scoringWorker ??= this.createWorker();
// stores the handler for retrieval when handling worker response message
const id = this.currentScoringRequestId++;
this.handlers.set(id, handleScoringResult);
try {
// stores the handler for retrieval when handling worker response message
const scoringRequestId = this.currentScoringRequestId++;
this.handlers.set(scoringRequestId, handleScoringResult );
this.scoringWorker.postMessage({
request: {
track: {
points: track,
},
ruleName: getScoringRuleName(league),
},
id: scoringRequestId,
id,
});
return scoringRequestId;
return id;
} catch (error) {
console.error('Error posting message to scoring worker:', error);
return -1;
Expand All @@ -70,24 +76,15 @@ export class Scorer {
* release resources related to the worker.
*/
public cleanup() {
if (!this.scoringWorker) {
return;
}
this.scoringWorker.onmessage = null;
this.scoringWorker.onerror = null;
this.scoringWorker.onmessageerror = null;
this.scoringWorker.terminate();
this.scoringWorker = undefined;
this.handlers.clear();
this.currentScoringRequestId = 0;
this.scoringWorker?.terminate();
}

private createWorker(): Worker {
const scoringWorker = new ScoringWorker();
scoringWorker.onmessage = (msg: MessageEvent<WorkerResponse>) => {
if (msg.data.id) {
// retrieve the handler and invoke it
this.handlers.get(msg.data.id)?.call(this, msg.data.response)
this.handlers.get(msg.data.id)?.call(this, msg.data.response);
if (msg.data.response.optimal) {
this.handlers.delete(msg.data.id);
}
Expand Down

0 comments on commit a2b9f5d

Please sign in to comment.