Categories
JavaScript

JavaScript OOP подготовка за изпит

Решение на задачата с курсове и студенти

course.js

define(function() {
    var Course;

    Course = (function() {
        function Course(title, totalScoreFormula) {
            this.title = title;
            this._totalScoreFormula = totalScoreFormula;
            this._students = [];
        }

        Course.prototype.addStudent = function(student) {
            this._students.push(student);
        };

        Course.prototype.calculateResults = function() {
            for (var i = 0; i < this._students.length; i++) {
                this._students[i].totalScore = this._totalScoreFormula(this._students[i]);
            }
        };
        Course.prototype.getTopStudentsByExam = function(number) {
            var sortedStudents = compareBy(this._students, 'exam');
            var topStudents = sortedStudents.slice(0, number);
            return topStudents;
        };
        Course.prototype.getTopStudentsByTotalScore = function(number) {
            var sortedStudents = compareBy(this._students, 'totalScore');
            var topStudents = sortedStudents.slice(0, number);
            return topStudents;
        };

        function compareBy(data, field) {
            data.sort(function(a, b) {
                if (a[field] < b[field]) return 1;
                if (a[field] > b[field])
                    return -1;
                return 0;
            });

            return data;
        };

        return Course;
    })();

    return Course;
});

student.js

define(function() {
    var Student;

    Student = (function() {
        function Student(data) {
            this.name = data.name;
            this.exam = data.exam;
            this.homework = data.homework;
            this.attendance = data.attendance;
            this.teamwork = data.teamwork;
            this.bonus = data.bonus;
        }

        return Student;
    })();

    return Student;
});