文章目录 通过两个对象轮换,按照是否访问实现内容长久保存rollup 的缓存实现 export default function (max) { //max 缓存容量var num, curr, prev;var limit = max || 1;function keep(key, value) {if (++num > limit) {prev = curr; // 超过容量时当前对象变成缓存reset(1);++num;}curr[key] = value;}// 1 是否清空缓存function reset(isPartial) {num = 0;curr = Object.create(null);isPartial || (prev=Object.create(null));}reset();return {clear: reset,has: function (key) {return curr[key] !== void 0 || prev[key] !== void 0;},get: function (key) {var val = curr[key];if (val !== void 0) return val;if ((val=prev[key]) !== void 0) { // 访问到缓存内容,让内容不过期keep(key, val); // 访问提取缓存,减少容量return val;}},set: function (key, value) {if (curr[key] !== void 0) {curr[key] = value;} else {keep(key, value); // 设置新内容,减少容量}}}; }