โœจclosure: manage grades

JS โŸฉ value โŸฉ function โŸฉ closure โŸฉ example โŸฉ 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