Re:Cappedstorage.js

From disqus.com, 2 Months ago, written in JavaScript, viewed 3 times. This paste is a reply to Re: mediaconfig.js from disqus.com - view diff
URL https://pastebin.freepbx.org/view/fef34c94 Embed
Download Paste or View Raw
  1. define('core/CappedStorage',[
  2.     'core/utils/storage',
  3. ], function (
  4.     storage
  5. ) {
  6.     'use strict';
  7.  
  8.     /**
  9.      * Like local storage but caps the number of items you can put into it.
  10.      * Once you hit the cap, the first item that was stored is removed
  11.      * in order to make room for the new item.
  12.      *
  13.      * @param {number} max      the maximum number of items in the store
  14.      * @param {string} queueKey key to be used by the underlying storage for this object
  15.      */
  16.     var CappedStorage = function (max, queueKey) {
  17.         this.max = max || 10;
  18.         this.queueKey = queueKey || '__queue';
  19.  
  20.         if (!this.getQueue())
  21.             this.setQueue([]);
  22.     };
  23.  
  24.     CappedStorage.prototype.set = function (key, value) {
  25.         var queue = this.getQueue() || this.setQueue([]);
  26.  
  27.         if (queue.length === this.max)
  28.             storage.remove(queue.shift());
  29.  
  30.         storage.set(key, value);
  31.  
  32.         queue.push(key);
  33.         this.setQueue(queue);
  34.     };
  35.  
  36.     CappedStorage.prototype.get = function (key) {
  37.         return storage.get(key);
  38.     };
  39.  
  40.     CappedStorage.prototype.remove = function (key) {
  41.         storage.remove(key);
  42.         var queue = this.getQueue() || [];
  43.  
  44.         for (var i = 0; i < queue.length; i++) {
  45.             if (queue[i] === key) {
  46.                 queue.splice(i, 1);
  47.                 break;
  48.             }
  49.         }
  50.         this.setQueue(queue);
  51.     };
  52.  
  53.     CappedStorage.prototype.clear = function () {
  54.         storage.clear();
  55.         this.setQueue([]);
  56.     };
  57.  
  58.     CappedStorage.prototype.getQueue = function () {
  59.         return storage.get(this.queueKey);
  60.     };
  61.  
  62.     CappedStorage.prototype.setQueue = function (queue) {
  63.         storage.set(this.queueKey, queue);
  64.         return queue;
  65.     };
  66.  
  67.     return CappedStorage;
  68. });
  69.  
  70. // https://c.disquscdn.com/next/next-core/core/CappedStorage.js

Replies to Re:Cappedstorage.js rss

Title Name Language When
Re: moment.js disqus.com javascript 2 Months ago.

Reply to "Re:Cappedstorage.js"

Here you can reply to the paste above