Recently I needed to manipulate with cookies using JavaScript, so I wrote a class:
function Cookies() {
var cookieLifeTime = null;
this.setCookie = setCookie;
this.getCookie = getCookie;
this.deleteCookie = deleteCookie;
this.setLifeTime = setLifeTime;
function setLifeTime(lifeTime) {
cookieLifeTime = lifeTime;
}
function setCookie(name, value) {
if (this.lifeTime !== null) {
var date = new Date();
date.setTime((date.getTime() + cookieLifeTime));
var expires = '; expires=' + date.toGMTString();
} else {
var expires = '';
}
document.cookie = name + '=' + value + expires + '; path=/';
}
function getCookie(name) {
name += '=';
var ca = document.cookie.split(';');
for(var i=0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ')
c = c.substring(1, c.length);
if (c.indexOf(name) === 0)
return c.substring(name.length, c.length); //Edited. Reduced not extra iterations
}
return null;
}
function deleteCookie(name) {
setCookie(name, '', -1);
}
}
I am not a JavaScript developer so maybe I've over-complicated things. Are there parts that can be optimized (I mean readability mostly)? I am also interested if there could be some edge-cases where this script will fail.