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

      

  • 相关阅读:
    window.onresize绑定事件以及解绑事件
    jqGrid中select带可编辑的
    ROS(机器视觉)
    Python(time模块)
    Python(random模块)
    Python迭代器
    Python生成器
    Python装饰器(函数)
    ROS(URDF机器人建模)
    ROS基础
  • 原文地址:https://www.cnblogs.com/wangxirui/p/14929962.html
Copyright © 2011-2022 走看看