JavaScript pixel to check track user

The code is just to check user session.

'use strict';  import Cookie from 'js-cookie'; import  _ from '../helpers';  module.exports = (event) => {   const spCookieName = 'sp';   const suCookieName = 'su';   try {     const e = event || {};      let sp = Cookie.get(spCookieName);     let isNewDevice = 1;     if (sp) {       Cookie.set(spCookieName, sp);       isNewDevice = 0;     } else {       sp = _.uuid();       Cookie.set(spCookieName, sp);       isNewDevice = 1;     }      let su = Cookie.get(suCookieName);     let isUserNewIn30Days = 0;     if (!su) {       Cookie.set(suCookieName, _.uuid(), { expires: 30 });       isUserNewIn30Days = 1;     }       let pID = Cookie.get('pID'); // page session ID     if (!pID) {       pID = _.uuid();       Cookie.set('pID', pID);     }      return {       uID: sp,       uNw: isNewDevice,       uUq: isUserNewIn30Days,       sID: Cookie.get('sID'),       pID: pID     };   } catch (e) {     return {};   } }; 

Replay

In some JavaScript engines (if I remember correctly, V8) cannot optimize code inside a try-catch. So while it may be negligible in this case, it's a practice to avoid. The workaround to it is to move out the code from the try catch to a function and call that function from the try-catch instead.

Not all your cookie names appear to be in variables. Move them into variables for consistency as well as to avoid hardcoding the cookie names everywhere.

Lastly, ES6 modules are by default run in strict mode. So no need to define 'use strict';.

The code can be simplified into the following. If you just separate the IO from the data manipulation, you can easily see patterns in the code which you can simplify.

import Cookie from 'js-cookie';
import  _ from '../helpers';

module.exports = (event) => {
  const uidCookieName = 'sp';
  const pidCookieName = 'pID';
  const sidCookieName = 'sID';
  const suCookieName  = 'su';

  const sID = Cookie.get(sidCookieName);
  const uID = Cookie.get(uidCookieName) || _.uuid();
  const pID = Cookie.get(pidCookieName) || _.uuid();
  const su  = Cookie.get(suCookieName)  || _.uuid();

  const uNw = !!Cookie.get(uidCookieName);
  const uUq = su ? 0 : 1; 

  Cookie.set(uidCookieName, uID);
  Cookie.set(pidCookieName, pID);
  Cookie.set(suCookieName, su, { expires: 30 });

  return { uID, sID, pID, uNw, uUq };
}

Category: javascript Time: 2016-07-29 Views: 0
Tags: javascript

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.237 (s). 12 q(s)