JSFiddle - React, Tailwind, and code Playground

by scriptwerx

JavaScript

/**
 * Persistent Data using localStorage and falling back to cookies.
 *
 * @description
 * Service to allow the storage of data within the browser Local Storage, falling back to Cookie.
 * This is not designed to store large amounts of data.
 *
 * @TODO: Does anything need to be hooked up for use within our native apps on mobile devices?
 */
(function() {

  'use strict';

  return angular.module('Scriptwerx.core', [])

  .service('storage', ['$window', '$document', function ($window, $document) {

      var prefix = 'swx_';
      var storageType = 'localStorage';
      var webStorage = $window[storageType];
      var forceCookie = false;
      var cache = {};
      var cookie = {
        expiry: 30,
        path: '/'
      };

      // Checks the browser to see if local storage is supported
      var browserSupportsLocalStorage = (function () {

        try {
          var supported = (storageType in $window && $window[storageType] !== null);
          var key = prefix + Math.round(Math.random() * 1e7);
          if (supported) {
            webStorage.setItem(key, '');
            webStorage.removeItem(key);
            return true;
          }
        }
        catch (/*e*/) {
          return false;
        }
      })();

      /**
       * Test if browser cookies are supported/enabled
       * @returns {boolean}
       */
      function testCookie() {
        try {
          return navigator.cookieEnabled || ('cookie' in $document[0] && ($document[0].cookie.length > 0 || ($document[0].cookie = 'test').indexOf.call($document[0].cookie, 'test') > -1));
        }
        catch (/*e*/) {
          return false;
        }
      }

      /**
       * Cookie fallback method - Update and store the cookie
       * @param key
       * @param value
       * [@param expire]
       * @returns {boolean}
       */
      function updateCookie(key, value) {

        if (!testCookie()) {
          return false;
        }

        try {
          var expiry = '',
           ...