Skip to content

Instantly share code, notes, and snippets.

@kosperera
Last active October 31, 2021 13:49
Show Gist options
  • Save kosperera/0719a0be63104aac03e61f63c6c2a087 to your computer and use it in GitHub Desktop.
Save kosperera/0719a0be63104aac03e61f63c6c2a087 to your computer and use it in GitHub Desktop.
Using JS conditionals
function ifGrade(marks) {
if (marks > 100) return 'Cheating is bad!';
else if (marks >= 90) return 'A+';
else if (marks >= 80) return 'A';
else if (marks >= 70) return 'B+';
else if (marks >= 60) return 'B';
else if (marks >= 50) return 'C';
else if (marks >= 40) return 'D';
else return 'F';
}
// console.log(ifGrade(75));
// "B+"
function whichGrade(marks) {
switch (true) {
case marks > 100: return 'Cheating is bad!';
case marks >= 90: return 'A+';
case marks >= 80: return 'A';
case marks >= 70: return 'B+';
case marks >= 60: return 'B';
case marks >= 50: return 'C';
case marks >= 40: return 'D';
default: return 'F';
}
}
// console.log(whichGrade(75));
// "B+"
var report = [
{ name: 'John', marks: 80 },
{ name: 'Smith', marks: 90 },
{ name: 'Doe', marks: 20 }
];
function printGradeOf(name) {
const found = report.find(function(student) {
return student.name === name;
});
// Change the whichGrade to ifGrade, if you wanna use if/else instead.
found ? console.log(found.name, whichGrade(found.marks)) : console.log('Did not find your kid', name);
}
function printGrades() {
console.log('Number of Students: ', report.length);
report.forEach(function(s) {
// Change the whichGrade to ifGrade, if you wanna use if/else instead.
console.log(s.name, whichGrade(s.marks));
});
}
var grades = [
{ min: 101, grade: 'Cheating is bad!' },
{ min: 90, grade: 'A+' },
{ min: 80, grade: 'A' },
{ min: 70, grade: 'B+' },
{ min: 60, grade: 'B' },
{ min: 50, grade: 'C' },
{ min: 40, grade: 'D' },
{ min: 0, grade: 'F', default: true }
];
// find the martching grade for the marks or the default.
function findGradeFor(marks) {
const found = grades.find(function(grade) { return grade.min <= marks || !!grade.default; });
return found.grade;
}
// findGradeFor(101);
// Cheating is bad!
// findGradeFor(75);
// "B+"
function addMarks(name, marks) {
report.push({ name, marks });
}
// addMarks('Sarah', 65);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment