From 842f164a8c4c2e36b9818c6ea4a3ab71262f52ac Mon Sep 17 00:00:00 2001 From: Mohammed9531 Date: Fri, 21 Jul 2017 22:19:51 -0500 Subject: [PATCH] refactor(*): Removed duplicate code. --- src/cookie.ts | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/cookie.ts b/src/cookie.ts index 88cf563..f023e9e 100644 --- a/src/cookie.ts +++ b/src/cookie.ts @@ -11,11 +11,9 @@ export class CookieService { * @returns existence of the cookie */ public check(name: string): boolean { - if (typeof document === "undefined") return false; // Check if document exist avoiding issues on server side prerendering - name = encodeURIComponent(name); - let regexp = new RegExp('(?:^' + name + '|;\\s*' + name + ')=(.*?)(?:;|$)', 'g'); - let exists = regexp.test(document.cookie); - return exists; + // Check if document exist avoiding issues on server side prerendering + if (typeof document === "undefined") return false; + return this.cookieHandler(name, 'test'); } /** @@ -26,13 +24,9 @@ export class CookieService { */ public get(name: string): string { if (this.check(name)) { - name = encodeURIComponent(name); - let regexp = new RegExp('(?:^' + name + '|;\\s*' + name + ')=(.*?)(?:;|$)', 'g'); - let result = regexp.exec(document.cookie); - return decodeURIComponent(result[1]); - } else { - return ''; + return decodeURIComponent(this.cookieHandler(name, 'exec')[1]); } + return ''; } /** @@ -88,7 +82,6 @@ export class CookieService { cookieStr += 'secure;'; } - // console.log(cookieStr); document.cookie = cookieStr; } @@ -112,9 +105,20 @@ export class CookieService { for (let cookieName of Object.keys(cookies)) { this.delete(cookieName, path, domain); } - } + /** + * @private + * Cookie Handler - Reusable Method + * + * @param {string} name Cookie's identification + * @param {string} methodName Method to be called + */ + private cookieHandler(name: string, methodName: string): any { + name = encodeURIComponent(name); + return (new RegExp('(?:^' + name + '|;\\s*' + name + ')=(.*?)(?:;|$)', 'g') as any) + [methodName](document.cookie); + } } export const Cookie = new CookieService();