HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JavaScript get total function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascripttotalgetfunction

Problem

I have two JS functions that return a total number for me based on some properties. It works fine but feels a bit 'clunky'. Would there be a cleaner way of doing this?

getTotalTrucks: function (data) {
    var noOfTrucks = 0;

    if (data.truck1 == "1") {
        noOfTrucks += 1;
    }
    if (data.truck2 == "1") {
        noOfTrucks += 1;
    }
    if (data.truck3 == "1") {
        noOfTrucks += 1;
    }
    if (data.truck4 == "1") {
        noOfTrucks += 1;
    }
    if (data.truck5 == "1") {
        noOfTrucks += 1;
    }

    return noOfTrucks ;
},

getTotalCars: function (data) {
    var noOfCars = 0;

    if (data.car1 == "2") {
        noOfCars += 1;
    }
    if (data.car2 == "2") {
        noOfCars += 1;
    }
    if (data.car3 == "2") {
        noOfCars += 1;
    }
    if (data.car4 == "2") {
        noOfCars += 1;
    }
    if (data.car5 == "2") {
        noOfCars += 1;
    }

    return noOfCars ;
}

Solution

Magic values

Your code compares to "1" and "2". What are these values supposed to convey? Use constants to signify what they mean.
Data structure

Your data structure is not great for the task you are trying to accomplish. Why not use a list containing car types? Why not at least split the data based on cars and trucks, so you can get away with just using Object.keys(data.cars).length or even a simple reduce?

{
    "cars" : {
         "car1": "2",
         "car2": "0"
    },
    "trucks" : {
         "truck1": "0",
         "truck2": "1"
    }
}


or

{
    "cars": [
        {
            "type": "car1",
            "status": "broken"
        },
        {
            "type": "car2",
            "status": "contains 4 wheels"
        }
    ],
    "trucks": [
        //you get the point
    ]
}

Code Snippets

{
    "cars" : {
         "car1": "2",
         "car2": "0"
    },
    "trucks" : {
         "truck1": "0",
         "truck2": "1"
    }
}
{
    "cars": [
        {
            "type": "car1",
            "status": "broken"
        },
        {
            "type": "car2",
            "status": "contains 4 wheels"
        }
    ],
    "trucks": [
        //you get the point
    ]
}

Context

StackExchange Code Review Q#147113, answer score: 4

Revisions (0)

No revisions yet.