The introduction

This topic in fact in the last share < small program fill pit record talked about > has talked about (big guy can bypass oh ~), but later in the group/comments are some students, mentioned some questions, ask if you can separately organize a more detailed share, explain the details and improve the shortcomings mentioned, if there is the following 👇. — “Share with your heart to make a warm siege lion, I am the chief pit filling officer — Su Nan”

Good morning, gentlemen, this is
@it · Flathead Alliance, I am
Chief pit filling officer ∙ Su NanShare with your heart to be a Siege Lion with temperature.


The public no. :
honeyBadger8Group: 912594095

Think about some

From the beginning of our contact with the front end, let’s start with the first familiar store related Cookie or analyze the closely related things in our life, such as Taobao, logistics, alarm clock, etc.

  • Cookie from the time you set, will be given a time, do not set the default session end expire;
  • Taobao shopping from your order and payment, it will give this goods set a delivery period of time, after this time automatically considered that you received goods (i.eEnd of the order);
  • Alarm clock you set the reminder time, in fact, is its expiration time;
  • Another example is the product demand related to your daily life. After the demand, the on-line time you give is the expiration time of this demand.
  • Popular point again, your birthday this year to the next year between the birthday is equivalent to set the period of validity time;

Above all, we can draw a conclusion that every event, every action, has a time, a node, and even we can blackout
localStorageWhy not give a mechanism to set expiration, because
sessionStorage,
CookieIt doesn’t meet our actual needs.

Implementation approach

Sorry, black localStorage is not perfect, a little exaggerated, combined with the above summary, the problem is simple, give localStorage an expiration time, everything is so easy? Whether it is or not, let’s look at the implementation:

A simple review

// Example 1: localStorage. SetItem ('test',1234567); let test = localStorage.getItem('test'); console.log(typeof test, test); // Example 2: localStorage['name'] = 'localStorage '; console.log(localStorage['name']); /* output: "1234567", "sunan", "1234567", "sunan", "number", "number", "number", "number", "number", "number", "number" */

Overwrite the set method:

  • First, there are three parameters, key, value and expired, which correspond to the key, value and expiration time respectively.
  • Expiration time units can be freely used, such as hours, minutes, days, etc.
  • Pay attention toPoint: The stored value may be an array/object. It cannot be stored directly. It needs to be convertedJSON.stringify.
  • How to set this time? Expand a field based on the key when the value is stored, such as key+’_expires_’, whose value is the current timestamp + expired time
  • Take a look at the code:
Set (key, value, crosscheck) {/* * crosscheck * @param {String} key * @param {String} value; * @param {String} expired time, in minutes, not necessary * @it · Flawhead Confederation-chief Flawhead ∙ shared, exchange: 912594095 */ let source = this.source; source[key] = JSON.stringify(value); if (expired){ source[`${key}__expires__`] = Date.now() + 1000*60*expired }; return value; }

Override the get method:

  • When obtaining data, judge the validity period of the time stored before, and compare with the current time;
  • But when the storageexpiredIs a non-required parameter, so the default is the current time +1, that is, the long-term valid;
  • If an expiration time is set at the time of storage, and it is found to be less than the current timestamp when retrieving, delete operation is performed, and null value is returned.
  • Pay attention toPoint: The stored value may be an array/object, which cannot be returned directly after being fetched. It needs to be convertedJSON.parse.
  • Take a look at the code:
Get (key) {/* * get method * @param {String} key * @param {String} expired when storage is not required, so it may not be available, Default is date.now +1 * @ by @it · Flyhead Brother Alliance - Chief Pit Filling-Officer ∙ Su Nan 912594095 */ const source = this.source, expired = source[`${key}__expires__`]||Date.now+1; const now = Date.now(); if ( now >= expired ) { this.remove(key); return; } const value = source[key] ? JSON.parse(source[key]) : source[key]; return value; }

Override the remove method:

  • Delete operation is simple,;
remove(key) { const data = this.source, value = data[key]; // Chief Pit Reclamation Officer ∙ Su Nan's column delete data[key]; delete data[`${key}__expires__`]; return value; }

Point of optimization:

  • Remember there was one last timeclassmate, it is socomments“Would it be a good idea to remove the cache in your constructor, or put it in your get and leave it there?” ;
  • Therefore, this optimization does an initial delete operation to clear the expired data;
  • Why notfor inBut the for?for inWhen iterating over the properties of an object, all properties on the prototype chain are accessed. Solution: UsehasOwnPropertyMethod filters or Object.keys return an array of their own enumerable properties;
class storage { constructor(props) { this.props = props || {} this.source = this.props.source || window.localStorage this.initRun(); } initRun(){/* * set * @param {String} key * @param {String} value; Need to convert json. stringify * @param {String} expired time, in minutes * @ by @it · Flat head - chief fill - in 912594095 */ const reg = new RegExp("__expires__"); let data = this.source; let list = Object.keys(data); if(list.length > 0){ list.map((key,v)=>{ if( ! reg.test(key )){ let now = Date.now(); let expires = data[`${key}__expires__`]||Date.now+1; if (now >= expires ) { this.remove(key); }; }; return key; }); }; }}

Conclusion:

The above is the summary and sharing for you today. Have you got it? Small program, sessionStorage, localStorage, are applicable, do some adjustment can oh, I hope today’s share can bring you a little growth, if you feel good, remember to pay attention to the public number below oh, the first time every week for you to push the latest share 👇.

More articles:

  • Easy-Mock doesn’t have one of the best spare tires
  • Immutability on React: Immutability on React: Immutability
  • The pit that interview stepped on, all here ~
  • You should do a summary of the front end performance optimization!
  • How to set an expiration time for localStorage?
  • Animation Bit by Bit – How to use CSS3 to draw out your 3D Rubik’s Cube?

Author: Su Nan –
Chief pit filling officer


Links:
https://blog.csdn.net/weixin_…


Communication:
912594095, official account:
honeyBadger8


This article is original and the copyright belongs to the author. Commercial reprint please contact
@it · Flathead AllianceAuthorized, non-commercial reprint please indicate the original link and source.