I am trying to clean up some old code, and was wondering if there was a clean one line solution to deal with something like the following.
function dates(format) {
var formats = ['DD/MM/YYYY','MM/DD/YYYY'];
// is there a one liner for something like this? If format is undefined this will throw an error when evaluating formats.indexOf(format)
format = (typeof format !== 'undefined' && formats.indexOf(format) >= 0) ? format : 'MM/DD/YYYY';
// ...
format is an argument to a function, and I would like to do some prelim checks to make sure the input is given, and meets criteria of being in an array.
Your code looks fine to me, except that
==undefinedcheck is superfluous.Note that this will not throw an exception if you call
dates()with no arguments at all.If you’ve a lot of code like this, you might consider using an utility function like
and then:
If you decide to use an object as Felix suggested, it’s better to structure it like this:
This looks stupid at the first glance, but has two important advantages. First, the
incheck is as simple asand second, you can extend that to provide aliases for your values: