nucliweb
12/28/2015 - 9:59 AM

Utility to work with cookies

Utility to work with cookies

const COOKIE_DELIMITER = ';'
const BLOCK_DELIMITER = '=';
const TOKEN_DELIMITER_REG_EXP = /\^|%5E/;

// Flatten Polyfill
Array.prototype.flatten = Array.prototype.flatten || function(){
  return this.reduce((a, b) => a.concat(Array.isArray(b) ? b.flatten() : b), [])
};

// Tap Polyfill
Array.prototype.tap = Array.prototype.tap || function({log = console.log}){
  log(this);
  return this;
};


const cookie = ({from, key}) => {
  const keyRegExp = new RegExp(key);
  return from
          .split(COOKIE_DELIMITER)
          .filter(c => c.match(keyRegExp))
          .map(block => {
            return block.split(BLOCK_DELIMITER)
                    .filter(u => !u.match(keyRegExp))
          })
          .map(info => {
            return info.map(token => token.split(TOKEN_DELIMITER_REG_EXP))
          })
          .flatten()
          .tap();
}