2
\$\begingroup\$

I have this JavaScript function which checks if the format has 'yyyy' and replaces 'yy' with 'y':

function validateDateFormat(format) { 
    if(format.indexOf("yyyy") != -1)
     return format.replace(/yy/g, 'y'); 
     else return format;
}

I feel like it can be simplified further. Can someone help me to refactor/optimize it?

\$\endgroup\$
3
\$\begingroup\$

This is already pretty simple. But I'd use the ternary operator ?: to make it a bit more compact:

function validateDateFormat(format) { 
    return format.indexOf("yyyy") == -1 ? format : format.replace(/yy/g, 'y'); 
}

Also, perhaps you can be a bit more accurate. There is a discrepancy between your check and the action taken:

  1. Check if string contains "yyyy"
  2. Replace all occurrences of "yy" with "y"

Perhaps it would be more accurate to change the action to this:

Replace "yyyy" with "yy" (only once)

That is:

function validateDateFormat(format) { 
    return format.indexOf("yyyy") == -1 ? format : format.replace(/yyyy/, 'yy'); 
}

Actually, and probably I should have started with this: since the .replace method returns the original string if there is no match, you could simplify even further:

function validateDateFormat(format) { 
    return format.replace(/yyyy/, 'yy'); 
}
\$\endgroup\$
1
\$\begingroup\$

The biggest problems I have with this function is not the simplicity, but the name and the the point of it.

The name

You are not validating anything here, but modifying, so the function should be named accordingly. How exactly depends of why you are doing this, which brings us to:

The point

A date format string is something that should be configurable, or at least stored in a single constant, so why not change that? To me it looks like you are trying to solve the wrong problem. (Not to mention the problems a two digit year has over a four digit year).

\$\endgroup\$
  • \$\begingroup\$ The DateFormat strings are configured in property files and they are generated from java locales and we are using jQuery to populate dates as per user locale preferences, and there is incompatibility between java and jquery dataformats. DateFormat with y givies two digit year in jQuery where as java uses yy format to generate two digit year and DateFormat with yy gives four digit year in jQuery where as java uses yyyy format to generate four digit year. Changing the dateformat in property file may break the java functionality so am modifying the dateformat in jQuery \$\endgroup\$ – RanPaul Nov 10 '14 at 15:37
  • \$\begingroup\$ @RanPaul That is actually a good reason. In that case call your function convertDateFormatToJQuery or something like that. \$\endgroup\$ – RoToRa Nov 11 '14 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.