Skip to content

Instantly share code, notes, and snippets.

@jmc734
Last active August 29, 2015 14:10
Show Gist options
  • Save jmc734/9b10c232754243cb42c1 to your computer and use it in GitHub Desktop.
Save jmc734/9b10c232754243cb42c1 to your computer and use it in GitHub Desktop.

Various Functions to Calculate the Number of Days in a Month (Non-Leap Year)

After reading Curtis McEnroe's article about creating a formula to calculate the number of days in a month, I got to thinking about a way to make it more compact. The first method I came up with (lotm.bitwise) shaved a few bytes of code but I figured it would also be a bit faster. I put together this jsPerf and found that in fact it was significantly quicker. I then came up with a few other approaches for comparison.

It turns out the lotm.lookupBitwise is both the most compact and the fastest (Chrome 39.0.2171.71 32-bit on Windows Server 2008 R2 / 7 64-bit).

/**
* Length of the Month
*/
var lotm = {
lookupTable: [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
curtisMcEnroe: function(x) {
return 28 + (x + Math.floor(x / 8)) % 2 + 2 % x + 2 * Math.floor(1 / x);
},
bitwise: function(x) {
var y;
return (y = 30 | (x >> 3 ^ x) & 1) ^ (~(x >> 2 | x | y) & 1) << 1
},
bitwiseEqual: function(x) {
return 28 | (x >> 3 ^ x) & 1 | (x!==2)<<1;
},
lookup: function(x) {
return this.lookupTable[x];
},
lookupBitwise: function(x) {
return 28 | (0x3BBEECC >> x >> x) & 3;
},
bigSwitch: function(x) {
switch (x) {
case 1:
return 31;
case 2:
return 28;
case 3:
return 31;
case 4:
return 30;
case 5:
return 31;
case 6:
return 30;
case 7:
return 31;
case 8:
return 31;
case 9:
return 30;
case 10:
return 31;
case 11:
return 30;
case 12:
return 31;
}
},
bigIf: function(x) {
if (x === 1) x = 31;
else if (x === 2) x = 28;
else if (x === 3) x = 31;
else if (x === 4) x = 30;
else if (x === 5) x = 31;
else if (x === 6) x = 30;
else if (x === 7) x = 31;
else if (x === 8) x = 31;
else if (x === 9) x = 30;
else if (x === 10) x = 31;
else if (x === 11) x = 30;
else if (x === 12) x = 31;
return x;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment