Jack Has Problems With His Dates

A long time ago, Jack needed a function to return a JavaScript date object which represented New Year’s Day for any year which he specified, or for the current year if none was provided.

This is what he came up with:

function getNewYearsDate(yr){

	var nyDate = new Date("");

	if ( typeof yr === "undefined"){
		var tmpDate = new Date();
		yr = tmpDate.getFullYear();


	return nyDate;

Of course, Jack tested his function carefully . . .

// returns Wed Jan 01 2020 00:00:00 GMT-0500 (Eastern Standard Time)
// returns Tue Jan 01 2019 00:00:00 GMT-0500 (Eastern Standard Time)

and seeing the results he expected to see, Jack pushed this change to production where it worked wonderfully for many months.

This morning, Jack identified a need for a similar function which represents July 4th/Independence Day. Because Jack is in a rush, he decides to copy and alter his getNewYearsDate function to handle returning the date for Independence Day in the United States (July 4th).

Here’s what he did:

function getIndependenceDate(yr){
	var idDate = new Date("");

	if ( typeof yr === "undefined"){
		var tmpDate = new Date();
		yr = tmpDate.getFullYear();


	return idDate;

But this time, when he tests his new function, he gets surprising results!

Tue Jan 01 2019 00:00:00 GMT-0500 (Eastern Standard Time)
Wed Jan 01 2020 00:00:00 GMT-0500 (Eastern Standard Time)

Can you see why the getNewYearsDate() function works, while the getIndependenceDate() function fails?

If so, how would you alter the getIndependenceDate() function so it returns the correct value?

How I Make Algorithms

I’ve been reading Clive Thompson’s Coders book, and it’s caused me to reflect upon the process I use for coming up with algorithms. I’ve come to realize this is one of those things which I do, but is incredibly difficult to explain to others– so this post is my effort to encapsulate “my process.”

  1. Become intrigued/obsessed with something (e.g. anagrams)
  2. Discover an online anagram finder
  3. Ask myself, “How would I go about building my own anagram finder?”
  4. Realize I have no idea, and beat myself up for not knowing
  5. Forget about building my anagram finder project
  6. Weeks later, coincidentally stumble across:
    1. Fermat’s notes on anagram comparison using prime numbers trick
    2. A code challenge to create anagram tester function
  7. Turn Fermat’s concept into a quick & dirty JavaScript function, areAnagrams().
  8. Feel good about my areAnagrams() milestone/accomplishment
  9. Realize Fermat approach hits integer bit-limit with medium length words.
  10. Convert areAnagrams() from prime numbers to “wordDNA” approach (i.e. case-insensitive letter sorting)
  11. Feel good about resolving limit in areAnagrams() function.
  12. Days later, realize wordDNA approach can be used to create a “rainbow table” of dictionary list– and now you’ve got the basic building parts of an online anagram finder.