Skip to content
Advertisement

if/else to call the function, the rest of the logic is identical

I am having a js code inside a js function. This contains an if else condition which contains same functionality, the only thing changed is the parameter.

So the only thing different is the parameter string you are passing to the functions. The if/else is used to call the function, the rest of the logic is identical.

Is it possible to call the function, the rest of the logic is identical?

return $(this).each(function () {
                if (coffeeId == "showCoffeeId") {
                    var todayDate = NoteWorklist.getDateTime("appleTime");
                    value.Year = todayDate.getFullYear();
                    value.Month = todayDate.getMonth() + 1;
                    value.Day = todayDate.getDate();
                    value.today = todayDate;
                    value.inputDate = todayDate;
                } else {
                    var todayDate = NoteWorklist.getDateTime("orangeTime");
                    value.Year = todayDate.getFullYear();
                    value.Month = todayDate.getMonth() + 1;
                    value.Day = todayDate.getDate();
                    value.today = todayDate;
                    value.inputDate = todayDate;
                }
            });

Advertisement

Answer

Just use the ternary operator:

return $(this).each(function () {
       var todayDate = NoteWorklist.getDateTime(coffeeID == "showCoffeeId" ? "appleTime" : "orangeTime");
       value.Year = todayDate.getFullYear();
       value.Month = todayDate.getMonth() + 1;
       value.Day = todayDate.getDate();
       value.today = todayDate;
       value.inputDate = todayDate;
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement