The introduction

This topic in fact in the last share < small program fill pit remember said > has been said (big guy can bypass oh ~), but later in the group/comments are some students, mentioned some questions, ask if you can separate arrange a more detailed share, explain the details and improve the mentioned deficiencies, so there is the following 👇.

I’m Su Nan, the chief pit filling officer, sharing with my heart to make a warm siege lion. Male Z: honeyBadger8, Group: 912594095

Think about some

Let’s start from the front end, the first familiar store related cookies or analyze taobao, logistics, alarm clock and other things closely related in our life.

  • Cookie from the time you set, will be given a time, do not set the default session end expiration;
  • Taobao shopping since you order payment, will give this goods to set up a time limit for receiving goods, after this time automatically think you receive goods (i.eEnd of the order);
  • Alarm clock you set the time to remind, in fact, is its expiration time;
  • Another example is the product demand related to your daily life. After the demand has passed, the online time you give is the expiration time of this demand.
  • In popular terms, your birthday this year to next year’s birthday is also equivalent to the setting of the validity period;

All of the above, we can draw a conclusion that any one thing, a behavior action, there is a time, a node, even we can black localStorage, is a perfect API, why can not give a set expiration mechanism, Because sessionStorage, cookies can not meet our actual needs.

Implementation approach

Sorry, black localStorage is not perfect, a bit exaggerated, comprehensive summary of the above, 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'] = 'jiangsu';
console.log(localStorage['name']);
/*
输出:
"1234567" ,'苏南',
这里要注意,1234567 存进去时是number 取出来就成string了
*/

Copy the code

Override the set method:

  • First, there are three parameters key, value, and expired, corresponding to the key, value, and expiration time respectively.
  • Units of expiration time can be used freely, such as hours, minutes, and days.
  • Pay attention toPoint: Stored values may be arrays/objects that cannot be stored directly and need to be convertedJSON.stringify.
  • How to set this time? Add a field to the key when the value is stored, for example: key+’expires‘, and its value is the current timestamp + expired expiration time
  • Take a look at the code:

set(key, value, expired) {
	/* * Set storage method * @param {String} key * @param {String} value Value, * @param {String} expired Time, in minutes, Not required * @ Shared by @IT· Flathead Alliance - Chief Pit Filling Officer, Nan Su */
	let source = this.source;
	source[key] = JSON.stringify(value);
	if (expired){
		source[`${key}__expires__`] = Date.now() + 1000*60*expired
	};
	return value;
}

Copy the code

Override the get method:

  • When obtaining data, determine the validity period of the stored time and compare it with the current time.
  • But when the storageexpiredIs a non-mandatory parameter. Therefore, the default value is current time +1, which is valid for a long time.
  • If the expiration time is set and the value is less than the current timestamp, the system deletes the timestamp and returns a null value.
  • Pay attention toPoint: The stored value may be an array/object, which cannot be returned directly after being fetched and needs to be convertedJSON.parse.
  • Take a look at the code:
get(key) {
	/* * get * @param {String} key * @param {String} expired; Default is date. now+1 * @ Shared by @it · Teamhead alliance - Chief Pit Filling Officer, Nan Su */
	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;
}

Copy the code

Override the remove method:

  • Delete operation is simple,;

remove(key) {
	const data = this.source,
		value = data[key];
	delete data[key];
	delete data[`${key}__expires__`];
	return value;
}
Copy the code

Point of optimization:

  • Remember last time there was aclassmate, it is socommentsCan delete cache from constructor be performed? Wouldn’t it be a good idea to put it in get without fetching it? ;
  • Why not?for inBut the for?for inWhen iterating through the properties of an object, all properties on the prototype chain will be accessed, solution: usehasOwnPropertyMethod filtering or object. keys returns an array of their own enumerable properties;

class storage {

	constructor(props) {
		this.props = props || {}
		this.source = this.props.source || window.localStorage
		this.initRun();
	}
	initRun(){
		/* * @param {String} key * @param {String} value Need to convert json.stringify * @param {String} expired expiration time in minutes * @ Shared by @it · Pacehead Union - Chief Pothole Filling Officer Su Nan */
		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);
					};
				};
				returnkey; }); }; }}Copy the code

Conclusion:

The above is the summary of today’s share, you GET? Small program, sessionStorage, localStorage, are applicable, make some adjustments can oh, I hope today’s share can bring you some growth, if you feel good, remember to like oh, by the way, the public Z number below is better, every week for you to push the latest share 👇👇.

Author: Su Nan – Chief Pit Filling Officer Link: blog.csdn.net/weixin_4325… Communication group: 912594095, public Good: honeyBadger8 Original article, copyright belongs to the author. Commercial reprint please contact @IT· Flathead brother alliance for authorization, non-commercial reprint please indicate the original link and source.