Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions frontend/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,19 +130,21 @@ function updateStatistics(subjects) {
return;
}

const scores = subjects.map(subject => subject.scoreValue);
const highest = Math.max(...scores);

// 計算加權平均
// 計算加權平均與最高分
let highest = -Infinity;
let totalWeightedScore = 0;
let totalWeight = 0;

subjects.forEach(subject => {
for (let i = 0; i < subjects.length; i++) {
const subject = subjects[i];
const score = subject.scoreValue;

if (score > highest) highest = score;

const weight = getSubjectWeight(subject.SubjectName);
totalWeightedScore += score * weight;
totalWeight += weight;
});
}
Comment on lines +138 to +147

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While the manual for loop is efficient, using a for...of loop is more idiomatic in modern JavaScript and improves readability by removing the need for manual index management. Modern engines optimize for...of to perform nearly identically to a standard for loop for array iterations.

Additionally, consider using highest = Math.max(highest, score) to maintain behavioral parity with the original implementation regarding NaN values. The current if (score > highest) logic will ignore NaN scores, whereas the original Math.max(...scores) would result in NaN if any score was invalid. If all scores happen to be invalid, the current code would incorrectly display -Infinity in the UI.

    for (const subject of subjects) {
        const score = subject.scoreValue;

        highest = Math.max(highest, score);

        const weight = getSubjectWeight(subject.SubjectName);
        totalWeightedScore += score * weight;
        totalWeight += weight;
    }


const weightedAvg = totalWeight > 0 ? totalWeightedScore / totalWeight : 0;

Expand Down
Loading