closure: manage grades

JSvaluefunctionclosureexample ⟩ manage grades

closure can be used as a function with private property (functions/variables)

// return a function (closure) that can add new grade.
function AddGrade(records) {

    // • original grades are imported from `records`
    // • record example : { id: 14, name: "Kyle", grade: 86 }
    let grades = records.map(recordToGrade);

    // ⭐ this function is returned
    return function addGrade(grade) {
        grades.push(grade);            // add new grade
        onlyKeepTop10Grades();
        log(grades);
        return grades;
    }

    // -------- other helper functions ---------

    function recordToGrade(record) {
        return record.grade;
    }

    function onlyKeepTop10Grades() {
        grades.sort((a, b) => b - a);   // sort in place, descending
        grades = grades.slice(0, 10);   // only keep top 10 grades
    }

}

// a closure instance
const addGrade = AddGrade([
    { id:  14, name: "Kyle" , grade: 86 },
    { id:  73, name: "Suzy" , grade: 87 },
    { id: 112, name: "Frank", grade: 75 },
    // many more records ...
    { id:   6, name: "Sarah", grade: 91 }
]);

// later
addGrade(81);    // [ 91, 87, 86, 81, 75 ]
addGrade(68);    // [ 91, 87, 86, 81, 75, 68 ]
addGrade(98);    // [ 98, 91, 87, 86, 81, 75, 68 ]

Last updated