• - (unregistered) in reply to Strider
    Strider:
    get some number for years

    if(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) leap! else dont!

    if(year % 4 == year % 100 == year % 400) leap!

  • Secure Programmer (unregistered) in reply to real_aardvark
    real_aardvark:
    From a Scientific Point Of View (ie one that takes into account Intelligent Design), this is as bad as using Fahrenheit or Centigrade to measure temperature.

    The equivalent to the Kelvin scale here is the Ussher scale, which is calibrated back to an origin of 9AM Oct 3 4004 "BC."

    Ignoring the rounding errors caused by not starting on the boundary between 28 and 29 Feb 4004 BC, you therefore have to take the following into account:

    (a) If the input is before -4004, the output is NaN. (I've always wanted to use that in integer arithmetic.) (b) For all other inputs, adjust by -4004 before applying the div 4, (mod 100 and mod 400) calculations. These are of course subtly different because of the irritating extra 4 that God chose to put in there.

    You can ignore leap-seconds, the precession of the Earth's axis and the slow degeneration of the Earth's orbit for any sensible date in this range because the numbers involved are too small to matter. Which just goes to show how clever Ussher was, and that Intelligent Design is obviously correct.

    And I'll bet they haven't factored that into VB.Net libraries ... just another reason to hate the goddamn language.

    The mythical intelligent design is a "scientific point of view"? WTF? I initially thought this post was sarcasm and a joke, but it seems to have been written seriously. Wow. Far out.

  • iMalc (unregistered)

    Has nobody noticed what happens in uploadtime when secs == 59?

    CAPTCHA: smile - yes you might once you notice the above.

  • (cs) in reply to Anonymous
    Anonymous:
    This is actually some of the best code I've ever seen posted in any of this site's forums.

    We all know a dozen different ways to compute the leap year. What matters is that the above code is clean and simple and straightforward. If another programmer comes along, he will instantly know what's going on.

    Quick maintainability is a hallmark of professional coding.

    Guess you didn't read any of the comments about optimization, eh?

    Most years aren't divisible by 4. Why check 75% of years for divisibility by 400, and if they aren't divisible by 400, then 100, and if that isn't true, 4?

    Strider's one-liner wins.

    That's very much a premature optimization. If you profiled it in an application, I highly doubt you would find any cases where you would need to go in and optimize that function.

    But there's no excuse for laziness anyway, it's far easier to just use the library functions. Why see if the year is divisible by 4, when you can ask another function if the year is a leap year?

  • (cs) in reply to GettinSadda
    GettinSadda:
    When the revolution comes there will be a special wall set aside to shoot programmers who use "(s)" to avoid figuring out plurals.
    Oh, and, by the way: English is not the only language available on this planet :-)
  • StressBomb (unregistered) in reply to mrprogguy

    "I AJAX would kill Flash, though. Flash is just evil, although not 100% evil. "

    Well, claiming that a technology is "modern" or "cool" or "evil" is a sure way to make many people who have a clue, realize that you don't.

  • PC Paul (unregistered) in reply to VGR
    VGR:
    This is actually some of the best code I've ever seen posted in any of this site's forums.

    We all know a dozen different ways to compute the leap year. What matters is that the above code is clean and simple and straightforward. If another programmer comes along, he will instantly know what's going on.

    Quick maintainability is a hallmark of professional coding.

    I agree, but I would always put unblocked if()'s on one line:

    bool
    isLeapYear(int year)
    {
        if (year % 400 == 0) return true;
        if (year % 100 == 0) return false;
        if (year %   4 == 0) return true;
        return false;
    }
    

    This makes it much less likely that some future modification will add a line in the middle. If it's too long to do that with, it should be in a block anyway.

    Actually, I'd be tempted to use a tip I first came across on TheDailyWTF and lay it out like this:

    bool
    isLeapYear(int year)
    {
        return (year % 400) ? true
             : (year % 100) ? false
             : (year %   4) ? true
             : /*default*/    false;
    }
    

    Whatever happened to TheDailyWTF anyway? This site is nearly as good, but...

    Captcha: doom. Posting my own code sample on here is asking for it.

  • Zylon (unregistered) in reply to Secure Programmer
    Secure Programmer:
    The mythical intelligent design is a "scientific point of view"? WTF? I initially thought this post was sarcasm and a joke, but it seems to have been written seriously. Wow. Far out.
    The best satire is written with a straight face. This has the added advantage of outing people too dense to detect satire on their own.
  • AndrewB (unregistered) in reply to Secure Programmer
    Secure Programmer:
    The mythical intelligent design is a "scientific point of view"? WTF? I initially thought this post was sarcasm and a joke, but it seems to have been written seriously. Wow. Far out.
    He was obviously joking.
  • ML (unregistered) in reply to vt_mruhlin
    vt_mruhlin:
    JavaScript in general pisses me off. My company has a web-based provisioning app that insists on using JavaScript to validate all the form data before you submit it.

    The developers on it set up the forms so that pressing enter in a textbox doesn't actually submit the form. They want me to have to press the submit button with my mouse, because that will "ensure" that I don't try to hack my way around the validation by turning JavaScript off....

    I tell the developer, "umm, I can just look at the source and find the URL it's posting to, send whatever data I want that way." His response? "That's why we do the same validation on the server side".....Why? Why bother?

    "Why bother" to which? Second validation on the server or preliminary validation on the client?

    The golden rule of web development is "never trust any incoming data from a browser". Therefore, everything coming in from the browser must be validated on the server. If that's not happening, then shame on the developer. If your "why bother" was for validation on the server side, then shame on you as well.

    Preliminary validation on the browser, without making calls to the server, is a very nice-to-have. With this, the user can get instant feedback on obvious errors without a round-trip to the server AND it takes a lot of unnecessary load off the server to boot. It's a win-win.

    However, you want to ride that fine line between putting enough validation to keep unnecessary load off the server, but not putting in so much that you expose the same business rules in two different places and creating a maintenance problem. Often, a good middle-ground is at the level of "are all required fields filled out?" and "Are there letters in the number field?" -- things that are relatively agnostic of specific business rules.

  • Kemp (unregistered) in reply to Andrew
    Andrew:
    Actually, the term ajax is rather overloaded. There are two characters in the Iliad named Ajax, a play about one of them was written by Sophocles. Other uses include at least four makes of automobiles, several ships, and two locomotives, at least nine sports teams, a band or two, a city in Canada, a missile, an asteroid, the cleanser and the dish soap, and even a kind of dinosaur.

    That's what happens when you name something after a mythical character.

    Maybe we could combine them somehow... Say a missile launching dinosaur that runs on Javascript

    (quoted from a friend)

  • (cs)

    AJAX is really named after a city east of Toronto:

    Ajax, Ontario

    the acronym came later. That's the REAL WTF.

  • bill (unregistered) in reply to jesse
    assuming one's piece of code will be out of service in 93 years from now, mod 4 is an adequate check. it's not correct but why bother..

    And if someone uses/extends/includes your code and they input a historical date, do date math, etc?

    Why would you actually go to the effort to do things the wrong way?

  • Matthew (unregistered) in reply to Just a number

    Pray tell, what catastrophic event will spell the end of mankind in the year 3002 ?

  • (cs) in reply to -

    Come on guys...

    A directory:

    .../leapyears/

    populated with files:

    1900, 1901, 1902, 1903, 1905, 1906, 1907, 1909, ... 2001, 2002, 2003, 2005, ...

    Then we could laugh that it's: a) inverted logic b) all sorts of applicable file-not-found gags

  • bill (unregistered) in reply to rgz
    That's just amazing to see how many coders actually focus on number representation ( as a string ) instead of properties ( modulo, comparison to 0, integer truncation ... ).
    Excusable for teenagers, but not for professionals. Not even non-programmers.
    
    I remember similar cases in older WTFes, like checking if a number starts with "-".</div></BLOCKQUOTE>
    

    I've seen "professional" programmers who don't know that, say, an IPv4 IP address is a 32-bit number. I've come across IPs stored in databases as CHAR(15)s, people doing "subnetting" by splitting on periods, all sort of abuses. I'm not really all that surprised when I see stuff like numbers treated as strings. A lot of the free JavaScript and PHP stuff has similar WTFs.

  • Ultimape (unregistered)

    I don't think its premature optimization... typically code like this is reused many times in multiple projects. While in your particular project, it might only be ran .01% of the time, another project might use it every time a database transaction is ran, which might be the entire point of the program (thus running a good deal more of the time).

    If you think about it in that sense, you realize that the weight of the code's optimization is potentially spread out in parallel over all the projects that include it. Thusly, the effectiveness of one optimization could be more than originally thought.

    This is espcially true with javascript, and how it is copied and pasted from website to website on a regular basis.

    Besides, I did that optimization instinctually when I went through and tried to write that code... shortcircuiting is a tool that should be used when availble, regardless. Its such a simple bit of tweaking that when applied uniformially, can reduce a large amount of comparitors.

    captcha: gotcha, like I just gotcha with a burn.

  • Tim (unregistered)
  • PabloHoney (unregistered) in reply to Anon
    Anon:
    AJAX (Asynchronous JavaScript and XML) is really starting to piss me off, because I'm starting to hear demands that it be used in totally inappropriate places.

    Places that make it obvious that the person has absolutely no idea what AJAX actually means, let alone what it does.

    I'd have to go searching through my inbox, but I believe I've actually had someone seriously suggest that XML be replaced with AJAX. I'm really not sure where to start on that one.

    And, of course, there were the numerous suggestions that web services be replaced with AJAX, never mind that AJAX is essentially a method of communicating with a web service.

    Plus there are the people who've started to use AJAX to mean "any webpage with JavaScript on it" which is also annoying.

    AJAX isn't really anything new - it's just a new term for an old trick.

    Captcha: scooter (as in Libby?)

    A long time ago (well 4 or 5 years ago...) In a galaxy far, far away... I worked on an intranet app using classic asp and (have to restrain myself when typing) a VB middle tier, as the app was (at the time) fairly simple and XML and XSL(T) was all the rage the asp was just a transform engine: calling the VB tier, getting XML back and transforming it into HTML. As the app grew (scope creep: good old PMs), so the amount of XML that needed to be transformed grew and MSXML n (can't remember the version, thank God) couldn't cope. So, guess what? We got back only the data that was required for initial page display, then as users expanded nodes in our grid, we got the data that was needed for that part of the page and did a partial page update.

    If only I'd come up with a fancy TLA or FLA and posted about it at the time: I could be rich...

    One million dollars...

    Ah well, back to the real world.

    May the force be with you...

  • (cs) in reply to Paul
    Paul:
    What's even more of a WTF is that the leap year calculation is WRONG. Leap years are years that are divisible by 4, unless they're divisible by 100, unless they're divisible by 400. The year 1900 was not a leap year, 2000 was.
    Don't worry, code like that will not last until the end of the decade. (with luck)
  • guy (unregistered) in reply to Ultimape
    Ultimape:
    I don't think its premature optimization... typically code like this is reused many times in multiple projects. While in your particular project, it might only be ran .01% of the time, another project might use it every time a database transaction is ran, which might be the entire point of the program (thus running a good deal more of the time).

    If you think about it in that sense, you realize that the weight of the code's optimization is potentially spread out in parallel over all the projects that include it. Thusly, the effectiveness of one optimization could be more than originally thought.

    This is espcially true with javascript, and how it is copied and pasted from website to website on a regular basis.

    Besides, I did that optimization instinctually when I went through and tried to write that code... shortcircuiting is a tool that should be used when availble, regardless. Its such a simple bit of tweaking that when applied uniformially, can reduce a large amount of comparitors.

    captcha: gotcha, like I just gotcha with a burn.

    It is totally a premature optimization. A couple of mod operations are nothing compared to a database transaction. This would basically have to run as one of the most expensive operation in a loop millions of times before you would see any gain at all from optimization.

  • Robert (unregistered)

    Not that anyone will read through over 100 comments to get here, but I have to defend my function in actionscript. Granted, it was a little lazy to put an "(s)" at the end of the string, but that wasn't really the point. The point was to show what someone (who is working professionally and making more money than myself) can butcher in 50 lines of javascript and still not have correct output. The actionscript function was to show how you can build a similar function with correct output in 4 lines. If you test the javascript function with some numbers, you'll see what I mean easier than trying to wade through it. And lastly, 3500 was the number of bytes someone arbitrarily decided to could be transferred per second using a 56k connection. Probably the same dude who wrote the first function....

  • Strider (unregistered) in reply to -
    -:
    Strider:
    get some number for years

    if(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) leap! else dont!

    if(year % 4 == year % 100 == year % 400) leap!

    Good Idea, xept you always do 3 comparisons, also 2001, 2002, 2003 would all be leap years! !=P

    close, but no cigar.

    personally, except for reverse logic (which some consider bad programming practice, and its harder to read), i think the negative checking is optimal no?

    you know, like someone said earlier:

    if (year % 4 != 0) return false if (year % 100 != 0) return true if (year % 400 != 0) return false return true

  • Strider (unregistered) in reply to Strider

    or better yet like this right, one liner?

    return year % 4 != 0 ? false : year % 100 != 0 ? true : year % 400 != 0 ? false : true;

  • (cs) in reply to real_aardvark
    real_aardvark:
    From a Scientific Point Of View (ie one that takes into account Intelligent Design), this is as bad as using Fahrenheit or Centigrade to measure temperature.

    The equivalent to the Kelvin scale here is the Ussher scale, which is calibrated back to an origin of 9AM Oct 3 4004 "BC."

    Ignoring the rounding errors caused by not starting on the boundary between 28 and 29 Feb 4004 BC, you therefore have to take the following into account:

    (a) If the input is before -4004, the output is NaN. (I've always wanted to use that in integer arithmetic.) (b) For all other inputs, adjust by -4004 before applying the div 4, (mod 100 and mod 400) calculations. These are of course subtly different because of the irritating extra 4 that God chose to put in there.

    You can ignore leap-seconds, the precession of the Earth's axis and the slow degeneration of the Earth's orbit for any sensible date in this range because the numbers involved are too small to matter. Which just goes to show how clever Ussher was, and that Intelligent Design is obviously correct....

    Wow! That will make calculations of Ancient Egyptian and Mesopotamian mortgage tables much easier. Thank you.
  • Lihtox (unregistered)

    This seems to work in C; wouldn't recommend it. :) (^ is exclusive-or.)

    leap=!(year%4)^!(year%100)^!(year%400);

  • (cs) in reply to JohnB
    JohnB:
    ... None of the software I've written was around in 1900, it was around in 2000, it won't be around in 2100. When I was doing all the Y2K remediation, we never worried about whether 2100 was or wasn't a leap year (except for the people who were remediating COBOL code).
    Well, I hope you put that restriction on page one of your eight meters of documentation.
  • (cs)

    If you really want to be picky then your algorithm should take into account that the formula for leap years might change in the future and it hasn't always been the same in the past. Probably the best way is to use the date functions of the language to check for Feb29. That way your code is automatically updated with the language if changes are made.

    Some people are criticising the use of just a simple mod four check. Of course you would'nt use such a simplification for a reusable function. However in some cases it might be appropriate. For example if you're sanitizing you input for a particular date range anyway, then you might not need to worry. If it was an embedded system like a wrist watch, then I'd probably stick with just the mod four check. Another thing to consider is that generally the more complex your code is the more likely you are to make mistakes. If you mess up the logic then your code might work fine in your tests on this years data, and then corrupt data four years from now. This is simple enough though that I would probably almost always just do it right, because just figuring out whether a simple mod four check might fail would be almost as time consuming as implementing the full algorithm.

    Another problem with the WTF example is that it checks for a period. I don't know about how Javascript handles it but in some locales the decimal point isn't a point but rather a comma.

  • John (unregistered) in reply to guy

    Agreed.

    Coding an incomplete leap year function is very likely a premature optimization. Fire up a profiler AFTER you have an application written and THEN tell us if the leap year function is a performance hit when in actual use.

    There are too many benefits to coding it right the first time.

    • It's correct
    • If people reuse it, they won't be duplicating an incomplete function (think about younger programmers who may not know better when they copy the code)
    • It will never be the source of an annoying leap year bug when certain conditions (potentially unforeseeable) are encountered

    Our job as developers is to create correct code. As far as performance goes, choose algorithms/data structures intelligently, then use a profiler to find out where the actual bottlenecks are.

    Rationalizing writing incomplete functions or using code that has known side effects that will "never happen" is just arrogance on display. We don't always know better as developers, even if we think we do.

  • Chris (unregistered) in reply to aikii

    Excusible for teenagers my ass. Maybe someone who's just starting out and doesnt know that it's more logical to compare a number to a number using built in functions/properties/operators, etc -- But I'm 17 and would rather choke myself with my wireless mouse cord than code like that

    I'm just getting over the negative number one posted a few weeks ago:

    if (number.toString().substr(0,1) == '-') { ...

    captcha: ewww (yes, this code was)

  • (cs) in reply to Anon
    Anon:
    Plus there are the people who've started to use AJAX to mean "any webpage with JavaScript on it" which is also annoying.

    I was at a meeting a few weeks ago in which a "user design expert" noted that the UI we were starting to think about would, of course, use Ajax to provide things like right-click menus. Luckily, he was on the other end of an intercontinental phone line, so I wasn't quite able to get my hands around his neck.

    Anon:
    AJAX isn't really anything new - it's just a new term for an old trick.

    You're all wrong. Ajax is my dog. And no, before anyone asks, he cannot learn new tricks ...

  • (cs)

    For those worried about a mod four version of the leap year function being reused by uninformed programmers, a simple partial solution is to include a comment that mod four might not work for years not between 1901 and 2099.

    The simple mod four algorithm does work for 2000 by the way, so it has a decent almost 200 year range of validity around the present.

  • Aaron (unregistered) in reply to RobFreundlich

    [quote user="RobFreundlich"][quote user="Anon"]Plus there are the people who've started to use AJAX to mean "any webpage with JavaScript on it" which is also annoying.[/quote]

    zOMG I'm SICK of that!!! Almost as much as I am about people referring to AJAX as a "technology".

    Why is it that people think "super pimp JS" == "AJAX"? Damn corporati and their buzzwords... grumblegrumble

  • Bob Villa (unregistered)

    ///

    /// Short and unreadable method to determine if the given year /// is a leap year. /// /// <param name="year">The year to check</param> /// <returns></returns> public bool IsLeapYear(int year) { return (year%400 == 0 || (year%100 != 0 && year%4 == 0)); }

  • PS (unregistered) in reply to aikii
    aikii:
    That's just amazing to see how many coders actually focus on number representation ( as a string ) instead of properties ( modulo, comparison to 0, integer truncation ... ).

    Excusable for teenagers, but not for professionals. Not even non-programmers.

    I remember similar cases in older WTFes, like checking if a number starts with "-".

    If this wouls stop with numbers, I'd be happy. Check the E4X (ECMAScript/JavaScript for XML) specification. The goal of the language (providing an easy-to-use XML API) may have been a sucess but some of the people who wrote this apparently couldn't think in anything else than strings either. There are some places where it literally demands that implementations must toString() XML objects, manipulate the string representation and the parse them back in. Good luck integrating that in existing DOM APIS...

  • Charles Bretana (unregistered)

    ahhh, grasshopper, javascript already know if is leapyear!

    function IsLeapYear(year) { var LastDayinFeb = new Date(year, 3, 0); return (LastDayinFeb.getDate() == 29); }

  • Charles Bretana (unregistered) in reply to Charles Bretana
    Charles Bretana:
    ahhh, grasshopper, javascript already know if is leapyear!

    function IsLeapYear(year) { var LastDayinFeb = new Date(year, 3, 0); return (LastDayinFeb.getDate() == 29); }

    or, to be terse,

    function IsLeapYear(year){return (new Date(year, 3, 0)).getDate() == 29);}

  • this forum software sucks (unregistered)

    thats some pretty bad stuff, JUST LIKE THIS FORUM SOFTWARE

  • (cs) in reply to ML
    ML:
    "Why bother" to which? Second validation on the server or preliminary validation on the client? ...If your "why bother" was for validation on the server side, then shame on you

    Yeah, my poor writing skills are the real WTF. I was referring to the client side validation.

    You raise a good point about saving server load; hadn't really thought about it that way, but I think in some cases it's doing more than just a "is it filled out".
    Range checking on some fields, for example... We changed the possible values from 0 < n < 100 to -1 < n < 100. Somebody forgot to update the validator...

  • Just a number (unregistered)

    While I agree that optimizing a leap-year function is an overkill, it would still make more sense to put year%4 test first, as this is (I think) most people would test first (rules first, then exceptions).

    Of course, the major WTF here is the solar system itself and/or our insistence on a circular calendar system where the days start over each year.

  • mcguire (unregistered) in reply to Cartroo

    Only as many as there are numbers which are divisible by 400.

  • reinventTheWheel (unregistered)

    So many leap year algorithms, in Java no less, and I only see one mention of

    java.util.GregorianCalendar.isLeapYear(int year)

    WTF?

  • workWithRob (unregistered)

    Now we know why there was so much confusion. We were in Java, not Javascript? Wait, do I have that backwards?

  • marsvin (unregistered) in reply to Unomi

    Maybe but those people don't post here ;)

    ... I hope o_o

  • sol (unregistered)

    AJAX - when you say hey to your pal named Jax! AJAX!

    Really lets call it Web 2.0 instead and then we can all be impressed...

    function HttpRequest()
    {
    var ret = new Object();
    								
    if (window.XMLHttpRequest)
    {	// Mozilla/Safari
    ret = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {	// IE
    ret = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {	//bitch!!!
    alert("bitch");
    ret = null;
    }
    				
    return ret;
    }
    
    

    I know let's use that and a database and

    document.bodyGetHttp.open("POST","GetContentFromDB.aspx",true);	document.chatGetHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");	document.bodyGetHttp.onreadystatechange = function()
    {
    if (document.bodyGetHttp.readyState == 4)
    {
    document.body.innerHtml = document.bodyGetHttp.responseText;
    }
    };

    yeah, and that page uses black magic to tell what content to load ;)

    and, btw the code is ill formatted, but just be glad it had a CrLf at all it doesn't have to...

  • sol (unregistered)

    AJAX - when you say hey to your pal named Jax! AJAX!

    Really lets call it Web 2.0 instead and then we can all be impressed...

    function HttpRequest()
    {
    var ret = new Object();
    								
    if (window.XMLHttpRequest)
    {	// Mozilla/Safari
    ret = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {	// IE
    ret = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {	//bitch!!!
    alert("bitch");
    ret = null;
    }
    				
    return ret;
    }
    
    

    I know let's use that and a database and

    document.bodyGetHttp.open("POST","GetContentFromDB.aspx",true);	document.chatGetHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");	document.bodyGetHttp.onreadystatechange = function()
    {
    if (document.bodyGetHttp.readyState == 4)
    {
    document.body.innerHtml = document.bodyGetHttp.responseText;
    }
    };

    yeah, and that page uses black magic to tell what content to load ;)

    and, btw the code is ill formatted, but just be glad it had a CrLf at all it doesn't have to...

  • dak (unregistered)

    Do a Google search for "javscript email validation"

    First link you get: function echeck(str) {

    	var at="@"
    	var dot="."
    	var lat=str.indexOf(at)
    	var lstr=str.length
    	var ldot=str.indexOf(dot)
    	if (str.indexOf(at)==-1){
    	   alert("Invalid E-mail ID")
    	   return false
    	}
    
    	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
    	   alert("Invalid E-mail ID")
    	   return false
    	}
    
    	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
    	    alert("Invalid E-mail ID")
    	    return false
    	}
    
    	 if (str.indexOf(at,(lat+1))!=-1){
    	    alert("Invalid E-mail ID")
    	    return false
    	 }
    
    	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
    	    alert("Invalid E-mail ID")
    	    return false
    	 }
    
    	 if (str.indexOf(dot,(lat+2))==-1){
    	    alert("Invalid E-mail ID")
    	    return false
    	 }
    	
    	 if (str.indexOf(" ")!=-1){
    	    alert("Invalid E-mail ID")
    	    return false
    	 }
    
    	 return true					
    }
    

    function ValidateForm(){ var emailID=document.frmSample.txtEmail

    if ((emailID.value==null)||(emailID.value=="")){
    	alert("Please Enter your Email ID")
    	emailID.focus()
    	return false
    }
    if (echeck(emailID.value)==false){
    	emailID.value=""
    	emailID.focus()
    	return false
    }
    return true
    

    }

    Yuck. Where's a regex when you need one?

  • jesse (unregistered) in reply to jesse
    assuming one's piece of code will be out of service in 93 years from now, mod 4 is an adequate check. it's not correct but why bother..

    hah since this was declared "a big wtf" by several others, let me explain what I meant with the word "assuming" in the beginning. If I know I can do that assumption it's adequate, what if there is no big picture.

    I can do the correct implementation but if this function was ever required from me I probably would avoid it (unless, of course, it would calculate on other dates than the current). I work embedded, usually on too small targets (i.e. always think optimise for size, for all you windows wankers size is the bytes and the kilobytes and the megabytes, yes applications also occupy those) and that code will be useless long before the next century. Is that a reason good enough for you? This is not a defense for that javascript code (that won't be in embedded) but rather a beration of the know-it-alls crowding this site, trying to excel in their own brillance.

    And yeah some would call me lazy too, but let's call it optimised for speed.

  • (cs) in reply to Andrew
    Andrew:
    No actually, what matters is that the code is clean and simple and straightforward. Unless you have a _very_ special app, it's probably going to spend at most 0.01% of its time figuring out whether years are leap years. Which means that if you make the leap-year predicate a _million_ percent faster, your overall performance will improve by at most a hair over a hundredth of a percent. Now that's optimization time well spent!

    There is optimization then there is OPTIMIZATION.

    I agree that it isn't always necessary to spent a ton of time to hand tweak, hand write in assembly, every last bit of code to wring out every last bit of optimization.

    BUT when you can do optimization, for pretty much for free. Doesn't reduce the readibility/maintainability of the code. You should do it. Every little bit counts.

    Just simply moving the mod 4 check, and to a != and placing it at the top of the function, speeds this code up. Why not do it? Someone coming along latter is going to wonder WTF, will make the change (and you know every change has the potential to break code) It is easy to spot that this is an optimization. Its one a compiler can't make. The code is just as easy to read, and makes just as much sense.

    If you guys are the ones writing the software I use, no wonder it is freaking slow.

  • G Henkel-Wallace (unregistered)
    On a serious note: if I hear one more person talk about AJAX without being able to tell me what it means, I'll snap.
    Actually, the thing I hate is when someone mentions Ajax and feels they have to ostentatiously explain what it means ("Actually, I think a better approach would be to use Ajax. That's Asyncronous blah blah you know."). Yeah, I know. And now I suspect you don't know what those words mean.

Leave a comment on “JavaScript Hacks ”

Log In or post as a guest

Replying to comment #:

« Return to Article