funme / coding

loving && coding && living
0 stars 0 forks source link

掘金 #17

Open funme opened 6 years ago

funme commented 6 years ago

干货!防运营商劫持 - 掘金

funme commented 6 years ago

纯前端导出微信通讯录到 Excel - 掘金

funme commented 5 years ago

class Cache { 
  constructor() { 
    this.prefix = '_txz_'; // 设置数据前缀 
    this.tiemPrefix = '_txzTime_'; // 设置过期时间 前缀 
  } 

  /** 
   * @description: 存缓存数据 
   * @param {String} key 要存的数据键名 
   * @param {*} value 要存放的值 
   * @param {Number} expire 过期时间 默认没有过期时间 这里写的秒数 
   */ 
  set(key, value, expire = 0) { 
    try { 
      let prefixKey = String(this.prefix + key); 
      // FIXME: 严谨一点的判断应该使用 (value !== null) && (value.constructor === Object) 
      if (value.constructor === Object) { 
        let oldData = wx.getStorageSync(prefixKey); 
        wx.setStorageSync(prefixKey, {...oldData, ...value}); 
      } else { 
        wx.setStorageSync(prefixKey, value); 
      } 

      let seconds = parseInt(expire) || 0; 
      let prefixTimeKey = String(this.tiemPrefix + key); 
      // 设置过期数据 
      if (seconds > 0) { 
        let timestamp = Date.parse(new Date()); 
        timestamp = timestamp / 1000 + seconds; 
        wx.setStorageSync(prefixTimeKey, timestamp + ""); 
      } else { 
        wx.removeStorageSync(prefixTimeKey); 
      } 
    } catch (error) { 
      console.log(error); 
    } 
  } 

  /** 
   * @description: 存缓存数据 
   * @param {String} key 要取的数据的键名 
   * @param {*} def 默认返回 如果数据过期则返回默认值 
   */ 
  get(key, def) { 
    let deadtime = parseInt(wx.getStorageSync(String(this.tiemPrefix + key)) || ''); 
    // 判断是否设置了过期时间 
    if (deadtime) { 
      if (parseInt(deadtime) < Date.parse(new Date()) / 1000) { 
        this.remove(key); 
        if (def) { 
          return def; 
        } else { 
          return ''; 
        } 
      } 
    } 

    // 返回正常数据 
    let res = wx.getStorageSync(this.prefix + key) || ''; 

    return res || def; 
  } 

  remove(key) { 
    wx.removeStorageSync(String(this.prefix + key)); 
    wx.removeStorageSync(String(this.tiemPrefix + key)); 
  } 

  clear() { 
    wx.clearStorageSync(); 
  } 
} 
const cache = new Cache(); 
export default cache;
funme commented 5 years ago
funme commented 5 years ago
funme commented 5 years ago