Skip to content

Instantly share code, notes, and snippets.

@Alex1990
Last active August 29, 2015 14:22
Show Gist options
  • Save Alex1990/ce227e5567fa08eec267 to your computer and use it in GitHub Desktop.
Save Alex1990/ce227e5567fa08eec267 to your computer and use it in GitHub Desktop.
/**
* switch vs object
*/
var dateMethods = {
Y: 'FullYear',
M: 'Month',
D: 'Date',
h: 'Hours',
m: 'Minutes',
s: 'Seconds'
};
// Object map
function parseExpires1(str) {
var expires = new Date();
var lastCh = str.charAt(str.length - 1);
var value = parseInt(str, 10);
var method = dateMethods[lastCh];
if (method) {
expires['set' + method](expires['get' + method]() + value);
} else {
expires = new Date(str);
}
return expires;
}
// Switch style
function parseExpires2(str) {
var expires = new Date();
var lastCh = str.charAt(str.length - 1);
var value = parseInt(str, 10);
switch (lastCh) {
case 'Y': expires.setFullYear(expires.getFullYear() + value); break;
case 'M': expires.setMonth(expires.getMonth() + value); break;
case 'D': expires.setDate(expires.getDate() + value); break;
case 'h': expires.setHours(expires.getHours() + value); break;
case 'm': expires.setMinutes(expires.getMinutes() + value); break;
case 's': expires.setSeconds(expires.getSeconds() + value); break;
default: expires = new Date(str)
}
return expires;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment