|
class CookieManager { |
|
constructor(cookieName) { |
|
this.cookieName = cookieName; |
|
} |
|
|
|
getAllValues() { |
|
const cookieValue = this.getCookieValue(); |
|
if (cookieValue) { |
|
return JSON.parse(cookieValue); |
|
} |
|
return []; |
|
} |
|
|
|
addValue(value) { |
|
const values = this.getAllValues(); |
|
values.push(value); |
|
this.setCookieValue(values); |
|
} |
|
|
|
deleteValue(value) { |
|
const values = this.getAllValues(); |
|
const index = values.indexOf(value); |
|
if (index > -1) { |
|
values.splice(index, 1); |
|
this.setCookieValue(values); |
|
} |
|
} |
|
|
|
clearAllValues() { |
|
this.setCookieValue([]); |
|
} |
|
|
|
getCookieValue() { |
|
const cookies = document.cookie.split(';'); |
|
for (let i = 0; i < cookies.length; i++) { |
|
const cookie = cookies[i].trim(); |
|
if (cookie.startsWith(this.cookieName + '=')) { |
|
return cookie.substring(this.cookieName.length + 1); |
|
} |
|
} |
|
return null; |
|
} |
|
|
|
setCookieValue(values) { |
|
const cookieValue = JSON.stringify(values); |
|
document.cookie = `${this.cookieName}=${cookieValue}`; |
|
} |
|
} |
|
|
|
|
|
//usage |
|
|
|
// Create an instance of CookieManager with the desired cookie name |
|
const cookieManager = new CookieManager('myCookie'); |
|
|
|
// Add values to the cookie |
|
cookieManager.addValue('value1'); |
|
cookieManager.addValue('value2'); |
|
cookieManager.addValue('value3'); |
|
|
|
// List all values stored in the cookie |
|
const allValues = cookieManager.getAllValues(); |
|
console.log(allValues); // Output: ['value1', 'value2', 'value3'] |
|
|
|
// Delete a value from the cookie |
|
cookieManager.deleteValue('value2'); |
|
|
|
// List all values again to see the updated list |
|
const updatedValues = cookieManager.getAllValues(); |
|
console.log(updatedValues); // Output: ['value1', 'value3'] |
|
|
|
// Clear all values from the cookie |
|
cookieManager.clearAllValues(); |
|
|
|
// List all values after clearing |
|
const clearedValues = cookieManager.getAllValues(); |
|
console.log(clearedValues); // Output: [] |
|
|