• 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);
    }
    

      

  • 相关阅读:
    【转】很全的TeeChart for .NET中文教程
    对比两个flash金融图表Stock Chart vs AnyStock
    FusionCharts实例大全
    [译]金融图表AnyStock的9个使用技巧
    看懂SqlServer查询计划
    怎样修改MySQL的默认编码
    VS2003+自带水晶报表的打包部署(CS方式)
    ADO.NET 连接池理解
    临时表 & 表变量
    Eclipse 快捷键介绍
  • 原文地址:https://www.cnblogs.com/wangxirui/p/14929962.html
Copyright © 2020-2023  润新知