zoukankan      html  css  js  c++  java
  • localStorage设置过期时间

    export function getItemKeyList(): Array<string> {
      const keyList = [];
      for (let i = 0; i < localStorage.length; i += 1) {
        const key = localStorage.key(i);
        if (key) {
          keyList.push(`${key}`);
        }
      }
      return keyList;
    }
    
    export function clearExpiredKeys() {
      const keyList = getItemKeyList();
      keyList.forEach(key => {
        const match = key.match(/|||(d{13})$/);
        if (match) {
          // const uselessPart = match[0];
          const expiresAt = Number(match[1]);
          if (new Date().getTime() > expiresAt) {
            localStorage.removeItem(key);
          }
        }
      });
    }
    
    function clearKeysOf(unwrappedKey: string) {
      const keyList = getItemKeyList();
      const regExp = new RegExp(`${unwrappedKey}\|\|\|`);
      keyList.forEach(fullKey => {
        if (regExp.test(fullKey)) {
          localStorage.removeItem(fullKey);
        }
      });
    }
    
    function getTargetFullKey(unwrappedKey: string): string {
      const keyList = getItemKeyList();
      let result = '';
      keyList.forEach(fullKey => {
        const regExp = new RegExp(`^${unwrappedKey}\|\|\|`);
        if (
          regExp.test(fullKey)
        ) {
          result = fullKey;
        }
      });
      return result;
    }
    
    export function setItem(options: {
      key: string;
      value: string;
      expiresAt?: number;
    }): void {
      clearExpiredKeys();
      clearKeysOf(options.key);
    
      let expiresAtString = '';
      if (options.expiresAt) {
        expiresAtString = `${options.expiresAt}`;
        if (expiresAtString.length !== 13) {
          throw new Error(`Invalid expiresAt value: ${expiresAtString}`);
        }
      }
    
      const fullKey = `${options.key}|||${expiresAtString}`;
      localStorage.setItem(fullKey, options.value);
    }
    
    export function getItem(unwrappedKey: string): string|null {
      clearExpiredKeys();
      const targetFullKey = getTargetFullKey(unwrappedKey);
      return localStorage.getItem(targetFullKey);
    }
    
    export function removeItem(unwrappedKey: string): void {
      clearExpiredKeys();
      const targetFullKey = getTargetFullKey(unwrappedKey);
      localStorage.removeItem(targetFullKey);
    }
    

      

  • 相关阅读:
    运用vue-awesome-swiper实现一个slide居中一个缩小显示
    IntersectionObserver
    leetcode 加一
    Cuda总结
    webrtc 视频数据 采集 发送 接收 显示
    webrtc ice代码流程走读
    webrtc sdp 组建 流程以及 sdp协议解析
    webrtc 视频参数配置
    webrtc 线程整理
    webrtc turn协议
  • 原文地址:https://www.cnblogs.com/wangxirui/p/14929962.html
Copyright © 2011-2022 走看看