Search code examples
javascriptobjectcaseletters

Better way to make lower and upper case letters have the same value in object other than listing them all out?


So I made a basic GPA calculator, and it works great. My question though is, is there an easier/cleaner way to make it so I don't have to list the lower and upper case grade values in my object? Because I want to make it so no matter if it's a lower or uppercase letter the user enters, it still means the same. I tried doing the .toUpperCase() function but it didn't work or I just did it wrong, and I'm kind of stuck on how to do this, or if it's even possible and leaving it like this is fine. Thanks. Here is my object.

var gradeValues = {
    "A+": 4.33,
    "a+": 4.33,
    "A": 4.0,
    "a": 4.0,
    "A-": 3.67,
    "a-": 3.67,
    "B+": 3.33,
    "b+": 3.33,
    "B": 3.0,
    "b": 3.0,
    "B-": 2.67,
    "b-": 2.67,
    "C+": 2.33,
    "c+": 2.33,
    "C": 2.0,
    "c": 2.0,
    "C-": 1.67,
    "c-": 1.67,
    "D+": 1.33,
    "d+": 1.33,
    "D": 1.0,
    "d": 1.0,
    "D-": 0.67,
    "d-": 0.67,
    "F": 0,
    "f": 0
};

Here's the rest of the code if you're wondering.

var getGrade = function() {
    input1 = document.form.input1.value;
    input2 = document.form.input2.value;
    input3 = document.form.input3.value;
    input4 = document.form.input4.value;

    var inputArray = [input1, input2, input3, input4];

    document.getElementById("result").innerHTML = ((gradeValues[input1] + gradeValues[input2] + gradeValues[input3] + gradeValues[input4]) / 4) + " is your GPA";

    for(var i = 0; i < inputArray.length; i++) {
        if(inputArray[i] === "") {
            alert("You didn't enter a letter into all of the boxes.");
            document.getElementById("result").innerHTML = "";
            return false;
        }
        else if(isNaN(inputArray[i]) === false) {
            alert("You have to enter a letter, not a number!");
            document.getElementById("result").innerHTML = "";
            return false;
        }
    };

Solution

  • You could use only the lower case letters (or upper case, but always the same case) in your object

    var gradeValues = {
        "a+": 4.33,
        "a": 4.0,
        "a-": 3.67,
        "b+": 3.33,
        "b": 3.0,
        "b-": 2.67,
        "c+": 2.33,
        "c": 2.0,
        "c-": 1.67,
        "d+": 1.33,
        "d": 1.0,
        "d-": 0.67,
        "f": 0
    };
    

    and convert the input to lower case for access.

    gradeValues[input1.toLowerCase()]
    

    In this case I suggest to use a wrapper for the access to the object, like

    function getValue(grade) {
        return gradeValues(grade.toLowerCase()];
    }
    

    This helps to convert only at one place to make the conversion and not at any place where you make an access to gradeValues.