- //plik: student-list.ts
- import { Student } from "./student"
- export class StudentList {
- private subject: string
- private students: Student[]
- constructor(subject: string) {
- this.subject = subject
- this.students = []
- }
- public addStudent(student: Student) {
- this.students.push(student)
- }
- public removeStudent(name: string) {
- this.students = this.students.filter(student => student.getName() != name)
- }
- public toString(): string {
- return this.subject + 'nStudenci: ' + this.students.map(s => s.toString()).join('n---n')
- }
- }
- //plik: student.ts
- export class Student {
- private name: string
- private age: number
- private grades: Map<string, number[]> //np fizyka, [5, 4, 2, 4.5]
- constructor(name: string, age: number) {
- this.name = name
- this.age = age
- this.grades = new Map()
- }
- public getName(): string {
- return this.name
- }
- public addGrade(subject: string, grade: number) {
- if (this.grades.has(subject)) { //jeśli sa juz jakies oceny z przedmiotu 'subject'
- const currentGrades = this.grades.get(subject) //pobieramy wszystkie oceny z przedmiotu 'subject'
- currentGrades?.push(grade) //dodajemy nowa ocene
- this.grades.set(subject, currentGrades!) //zamieniamy dotychczasowa pare: przedmiot-oceny, na nową, z dodaną oceną
- } else { //jezeli wstawiamy pierwsza ocene z przedmiotu 'subject
- this.grades.set(subject, [grade])
- }
- }
- public average(subject: string): number {
- const currentGrades = this.grades.get(subject)
- let sum = 0
- currentGrades?.forEach(grade => sum += grade)
- if (!this.grades.has(subject)) {
- return 0
- } else {
- return sum / currentGrades!.length
- }
- }
- public toString(): string {
- const subjects = this.grades.keys()
- let grades = ''
- for (let subject of subjects) {
- grades += subject + ': ' + this.grades.get(subject) + 'n'
- }
- return `Nazwisko: ${this.name}nWiek: ${this.age}nOceny: ${grades}`
- }
- }
- // W klasie student zmień pola ocena1 i ocena2 na
- // oceny (typ: mapa składająca się z par: przedmiot, lista ocen)
- // zmień metodę średniaOcen; metoda ta bierze jako parametr nazwę przedmiotu
- // zmień też odpowiednio metodę toString
- // W pliku app.ts utwórz zmienną bestStudents, jest to mapa składająca
- // się z par: przedmiot-student, gdzie studentem jest student o
- // najwyższej średniej z danego przedmiotu
- import { Student } from "./student"
- import { StudentList } from "./student-list"
- const student = new Student('Nowak', 20)
- student.addGrade('fizyka', 4)
- student.addGrade('fizyka', 5)
- student.addGrade('biologia', 3)
- student.addGrade('matematyka', 2)
- student.addGrade('fizyka', 1)
- student.addGrade('biologia', 4)
- console.log(student.average('fizyka'))