-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
52 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,64 @@ | ||
|
||
export interface Student { | ||
// describe Student interface | ||
name: string; | ||
surname: string; | ||
age: number; | ||
married: boolean; | ||
grades: number[]; | ||
} | ||
|
||
export enum SortType { | ||
// describe SortType enum | ||
Name = 'name', | ||
Surname = 'surname', | ||
Age = 'age', | ||
Married = 'married', | ||
AverageGrade = 'grades', | ||
} | ||
|
||
// create SortOrder type | ||
export type SortOrder; | ||
export type SortOrder = 'asc' | 'desc'; | ||
|
||
export function sortStudents( | ||
students: Student[], | ||
sortBy: SortType, | ||
order: SortOrder, | ||
): Student[] { | ||
const sortedStudents = [...students]; | ||
|
||
function getAverageGrades(student: Student): number { | ||
return ( | ||
student.grades.reduce((sum, grade) => sum + grade, 0) | ||
/ student.grades.length | ||
); | ||
} | ||
|
||
switch (sortBy) { | ||
case SortType.Surname: | ||
case SortType.Name: | ||
sortedStudents.sort((a, b) => { | ||
return order === 'asc' | ||
? a[sortBy].localeCompare(b[sortBy]) | ||
: b[sortBy].localeCompare(a[sortBy]); | ||
}); | ||
break; | ||
|
||
case SortType.AverageGrade: | ||
sortedStudents.sort((a, b) => { | ||
return order === 'asc' | ||
? getAverageGrades(a) - getAverageGrades(b) | ||
: getAverageGrades(b) - getAverageGrades(a); | ||
}); | ||
break; | ||
|
||
default: | ||
sortedStudents.sort((a, b) => { | ||
return order === 'asc' | ||
? +a[sortBy] - +b[sortBy] | ||
: +b[sortBy] - +a[sortBy]; | ||
}); | ||
break; | ||
} | ||
|
||
export function sortStudents(students, sortBy, order) { | ||
// write your function | ||
return sortedStudents; | ||
} |