Fe-interview: [js] 第449天 模拟 localStorage 时如何实现过期时间功能

Created on 7 Jul 2020  ·  6Comments  ·  Source: haizlin/fe-interview

第449天 模拟 localStorage 时如何实现过期时间功能

作者:webVueBlog

3+1官网

我也要出题

js

Most helpful comment

class MyStorage {
  get(key) {
    const wrapValue = localStorage.getItem(key)
    if (wrapValue == null) {
      return undefined
    }

    const {value, expires} = JSON.parse(wrapValue)
    if ((expires != null && Date.now() < expires) || expires == null) {
      return value
    } 

    return undefined
  }

  set(key, value, period) {
    const wrapValue = { value };
    if (period != null) {
      wrapValue.expires = Date.now() + period;
    }

    localStorage.setItem(key, JSON.stringify(wrapValue));
  }
}

All 6 comments

在设置值的时候将当前时间一并写入,读取值的时候先判断当前时间是否在允许的时间范围

设置时设置一个存入时间戳,取出的时候判断当前的时间戳与存入时间戳是否在有效期内,没在有效期内读取就会失败

class MyStorage {
  get(key) {
    const wrapValue = localStorage.getItem(key)
    if (wrapValue == null) {
      return undefined
    }

    const {value, expires} = JSON.parse(wrapValue)
    if ((expires != null && Date.now() < expires) || expires == null) {
      return value
    } 

    return undefined
  }

  set(key, value, period) {
    const wrapValue = { value };
    if (period != null) {
      wrapValue.expires = Date.now() + period;
    }

    localStorage.setItem(key, JSON.stringify(wrapValue));
  }
}

function get(name) {
const record = JSON.parse(localStorage.getItem(name));
return record.time - Date.now() > 0 ? record: localStorage.removeItem('record');
}

function set(value) {
let record = {
time: Date.now() + 5000,
result: value
}
localStorage.setItem('record', JSON.stringify(record));
}

@liyan1105

class MyStorage {
  get(key) {
    const wrapValue = localStorage.getItem(key)
    if (wrapValue == null) {
      return undefined
    }

    const {value, expires} = JSON.parse(wrapValue)
-    if ((expires != null && Date.now() < expires) || expires == null) {
+    if (!expires || Date.now() < expires) {
      return value
    } 
-
+   localStorage.rmeoveItem(key)
    return undefined
  }

  set(key, value, period) {
    const wrapValue = { value };
    if (period != null) {
      wrapValue.expires = Date.now() + period;
    }

    localStorage.setItem(key, JSON.stringify(wrapValue));
  }
}

1.存储时记录下有效截止时间
2.取数据时判断是否超过有效时间,在有效期内则返回,不在则提示或返回空并且将其删除

Was this page helpful?
0 / 5 - 0 ratings

Related issues

undefinedYu picture undefinedYu  ·  3Comments

haizhilin2013 picture haizhilin2013  ·  3Comments

haizhilin2013 picture haizhilin2013  ·  3Comments

haizhilin2013 picture haizhilin2013  ·  3Comments

haizhilin2013 picture haizhilin2013  ·  3Comments