When a university asks for your GPA, it almost never means the average of your course grades. It means a credit-weighted average, where a four-credit course counts more than a one-credit lab. The difference can be large, and it is a good example of a tiny function that is easy to get subtly wrong.
The formula
For each course, multiply grade points by credits. Add those up, then divide by the total credits:
GPA = sum(points x credits) / sum(credits)
A small implementation
type Course = { name : string ; credits : number ; points : number } ;
export function weightedGpa ( courses : Course [ ] ) : number | null { const totalCredits = courses . reduce ( ( sum , c ) => sum + c . credits , 0 ) ; if ( totalCredits === 0 ) return null ; // nothing to average const qualityPoints = courses . reduce ( ( sum , c ) => sum + c . points * c . credits , 0 ) ; return Math . round ( ( qualityPoints / totalCredits ) * 100 ) / 100 ; }
Enter fullscreen mode
Exit fullscreen mode
Two details are worth noting.…