How to shorten switch case block converting a number to a month name?
JavascriptDateSwitch StatementDate FormatJavascript Problem Overview
Is there a way to write this on fewer lines, but still easily readable?
var month = '';
switch(mm) {
case '1':
month = 'January';
break;
case '2':
month = 'February';
break;
case '3':
month = 'March';
break;
case '4':
month = 'April';
break;
case '5':
month = 'May';
break;
case '6':
month = 'June';
break;
case '7':
month = 'July';
break;
case '8':
month = 'August';
break;
case '9':
month = 'September';
break;
case '10':
month = 'October';
break;
case '11':
month = 'November';
break;
case '12':
month = 'December';
break;
}
Javascript Solutions
Solution 1 - Javascript
Define an array, then get by index.
var months = ['January', 'February', ...];
var month = months[mm - 1] || '';
Solution 2 - Javascript
what about not to use array at all :)
var objDate = new Date("10/11/2009"),
locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
console.log(month);
// or if you want the shorter date: (also possible to use "narrow" for "O"
console.log(objDate.toLocaleString(locale, { month: "short" }));
as per this answer https://stackoverflow.com/questions/1643320/get-month-name-from-date from David Storey
Solution 3 - Javascript
Try this:
var months = {'1': 'January', '2': 'February'}; //etc
var month = months[mm];
Note that mm
can be an integer or a string and it will still work.
If you want non-existing keys to result in empty string ''
(instead of undefined
), then add this line:
month = (month == undefined) ? '' : month;
Solution 4 - Javascript
You could create an array instead and lookup the month name:
var months = ['January','February','March','April','May','June','July','August','September','October','November','December']
var month = months[mm-1] || '';
See the answer by @CupawnTae for the rational behind the code || ''
Solution 5 - Javascript
Be careful!
The thing that should immediately trigger alarm bells is the first line: var month = '';
- why is this variable being initialized to an empty string, rather than null
or undefined
? It may just have been habit or copy/pasted code, but unless you know that for sure, it is not safe to ignore it when you're refactoring code.
If you use an array of month names and change your code to var month = months[mm-1];
you are changing the behaviour, because now for numbers outside the range, or non-numeric values, month
will be undefined
. You may know that this is ok, but there are many situations where this would be bad.
For example, let's say your switch
is in a function monthToName(mm)
, and someone is calling your function like this:
var monthName = monthToName(mm);
if (monthName === '') {
alert("Please enter a valid month.");
} else {
submitMonth(monthName);
}
Now if you change to using an array and returning monthName[mm-1]
, the calling code will no longer function as intended, and it will submit undefined
values when it is supposed to display a warning. I'm not saying this is good code, but unless you know exactly how the code is being used, you can't make assumptions.
Or maybe the original initialization was there because some code further down the line assumes that month
will always be a string, and does something like month.length
- this will result in an exception being thrown for invalid months and potentially kill the calling script completely.
If you do know the entire context - e.g. it's all your own code, and no-one else is ever going to use it, and you trust yourself not forget you made the change sometime in the future - it may be safe to change the behaviour like this, but soooo many bugs come from this kind of assumption that in real life you're far better off programming defensively and/or documenting the behaviour thoroughly.
Wasmoo's answer gets it right (EDIT: a number of other answers, including the accepted one, have now been fixed too) - you can use months[mm-1] || ''
or if you would prefer to make it more obvious at a glance what's happening, something like:
var months = ['January', 'February', ...];
var month;
if (mm >= 1 && m <= 12) {
month = months[mm - 1];
} else {
month = ''; // empty string when not a valid month
}
Solution 6 - Javascript
For completeness I'd like to supplement to current answers. Basically, you can ommit the break
keyword and directly return an appropriate value. This tactic is useful if the value cannot be stored in a precomputed look-up table.
function foo(mm) {
switch(mm) {
case '1': return 'January';
case '2': return 'February';
case '3': return 'March';
case '4': return 'April';
// [...]
case '12': return 'December';
}
return '';
}
Once again, using a look-up table or date functions is more succinct and subjectively better.
Solution 7 - Javascript
You could do it using an array:
var months = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'];
var month = months[mm - 1] || '';
Solution 8 - Javascript
Here's another option that uses only 1 variable and still applies the default value ''
when mm
is outside of range.
var month = ['January', 'February', 'March',
'April', 'May', 'June', 'July',
'August', 'September', 'October',
'November', 'December'
][mm-1] || '';
Solution 9 - Javascript
You could write it as an expression instead of a switch, using conditional operators:
var month =
mm == 1 ? 'January' :
mm == 2 ? 'February' :
mm == 3 ? 'March' :
mm == 4 ? 'April' :
mm == 5 ? 'May' :
mm == 6 ? 'June' :
mm == 7 ? 'July' :
mm == 8 ? 'August' :
mm == 9 ? 'September' :
mm == 10 ? 'October' :
mm == 11 ? 'November' :
mm == 12 ? 'December' :
'';
If you haven't seen chained conditional operators before this may seem harder to read at first. Writing it as an expression makes one aspect even easier to see than the original code; it's clear that the intention of the code is to assign a value to the variable month
.
Solution 10 - Javascript
Building on Cupawn Tae's answer previous I'd shorten it to :
var months = ['January', 'February', ...];
var month = (mm >= 1 && mm <= 12) ? months[mm - 1] : '';
Alternatively, yes, I appreciate, less readable:
var month = months[mm - 1] || ''; // as mentioned further up
Solution 11 - Javascript
var getMonth=function(month){
//Return string to number.
var strMonth = ['January', 'February', 'March',
'April', 'May', 'June', 'July',
'August', 'September', 'October',
'November', 'December'
];
//return number to string.
var intMonth={'January':1, 'February':2, 'March':3,
'April':4, 'May':5, 'June':6, 'July':7,
'August':8, 'September':9, 'October':10,
'November':11, 'December':12
};
//Check type and return
return (typeof month === "number")?strMonth[month-1]:intMonth[month]
}
Solution 12 - Javascript
Like @vidriduch, I would like to underline the importance of i20y ("internationalisability") of code in nowadays' context and suggest the following concise and robust solution together with the unitary test.
function num2month(month, locale) {
if (month != Math.floor(month) || month < 1 || month > 12)
return undefined;
var objDate = new Date(Math.floor(month) + "/1/1970");
return objDate.toLocaleString(locale, {month: "long"});
}
/* Test/demo */
for (mm = 1; mm <= 12; mm++)
document.writeln(num2month(mm, "en") + " " +
num2month(mm, "ar-lb") + "<br/>");
document.writeln(num2month("x", "en") + "<br/>");
document.writeln(num2month(.1, "en") + "<br/>");
document.writeln(num2month(12.5, "en" + "<br/>"));
I try to stay as close as possible to the original question, i.e. transform numbers 1 to 12 into month names, not only for one special case, but return undefined
in case of invalid arguments, using some of the formerly added criticism to and contents of other answers.
(The change from undefined
to ''
is trivial, in case exact matching is needed.)
Solution 13 - Javascript
I'd go for wasmoo's solution, but adjust it like this :
var month = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
][mm-1] || '';
It is the exact same code, really, but differently indented, which IMO makes it more readable.