const log = console.info
console.clear()
class Timer {
static wait(delay, cb) {
return new Promise((resolve) => {
setTimeout(() => resolve(cb()), delay)
})
}
static count() {
let count = 0
setInterval(() => log(count++), 1000)
}
static countWith(cb) {
Timer.count()
cb()
}
static loop(cb, delay = 3000) {
let timer = setInterval(() => cb(timer), delay);
}
}
// Timer.wait(1000, () => log(1))
// Timer.countWith(start)
const arr = [
() => Timer.wait(1000, () => log(1)),
() => Timer.wait(2000, () => log(2)),
() => Timer.wait(3000, () => log(3)),
]
//异步递归
Promise.series = function (arr) {
const reducer = (tol, cur) => tol.then(cur)
return arr.reduce(reducer, Promise.resolve('start'))
}
// Promise.series(arr).then(() => log('end'))
// sessionStorage.setItem('num', '1')
// Promise.resolve('start').then(() => {
// return new Promise(resolve => {
// Timer.loop((timer) => {
// log('waiting response')
// if (sessionStorage.getItem('num')) {
// resolve()
// clearInterval(timer)
// }
// })
// })
// }).then(() => log('end'))
// p.then(() => log('end'))
// Promise.resolve('start').then(() => Timer.wait(1000, () => log(1))).then(() => log('end'))
// Promise.all(arr).then(val=>log(val))
// Promise.all([
// Timer.wait(1000, () => log(1)),
// Timer.wait(1000, () => log(2)),
// Timer.wait(1000, () => log(3)),
// ])
; (function (local) {
function isEmptyObject(e) {
for (let t in e) {
if (e.hasOwnProperty(t)) {
return false
}
}
return true
}
local.Storage.prototype['setObj'] = function (key, val) {
if (!isEmptyObject(key)) {
this.setItem(key, JSON.stringify(val))
}
}
local.Storage.prototype['getObj'] = function (key) {
if (this.hasObj(key)) {
return JSON.parse(this.getItem(key))
} else {
return null
}
}
local.Storage.prototype['hasObj'] = function (key) {
let result = this.getItem(key)
return !isEmptyObject(result)
}
class CacheManager {
static setSessionObj(key) {
return sessionStorage.setObj(key)
}
static getSessionObj(key) {
return sessionStorage.getObj(key)
}
static hasSessionObj(key) {
return sessionStorage.hasObj(key)
}
}
// sessionStorage.setItem('num', '')
// log(CacheManager.hasSessionObj('num'))
// log(sessionStorage.getItem('num'))
// log( sessionStorage.hasObj('num'))
// log(sessionStorage.getObj('num'))
// log(sessionStorage)
})(window)
// 算法规则
// 添加数据:
// 有新数据(意味着数据之前没有被缓存过)添加时,加入到列表头部
// 缓存到达最大容量时,需要淘汰数据多出来的数据,此时淘汰列表尾部的数据
// 当缓存中有数据被命中,则将数据移动到列表头部(相当于新加入缓存)
// 取数据:
// 如果没有该数据,返回-1
// 如果有该数据,取出该数据,并放在列表头部,并返回该数据
import collections
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.queue = collections.OrderedDict()
def get(self, key):
if key not in self.queue:
return -1
value = self.queue.pop(key)
self.queue[key] = value
return self.queue[key]
def put(self, key, value):
if key in self.queue:
self.queue.pop(key)
elif len(self.queue.items()) == self.capacity:
self.queue.popitem(last=False)
self.queue[key] = value
c = LRUCache(5)
for i in range(5,10):
c.put(i,10*i)
x = c.get(6)
print(c.queue)
// static mockRequest(config) {
// const fetch = function (idx) {
// return new Promise(resolve => {
// console.log(`start request ${idx}`);
// // 模拟请求时间
// let timeout = parseInt(Math.random() * 1e4);
// timeout = 1000
// setTimeout(() => {
// console.log(`end request ${idx}`);
// resolve(idx)
// }, timeout)
// })
// };
// if (CacheManager.hasSessionObj(url)) {
// return { isCache: true, ...CacheManager.getSessionObj(url) }
// }
// return fetch(config.baseUrl + config.url);
// }
function handleFetchQueue(urls, max, callback) {
const urlCount = urls.length;
const requestsQueue = [];
const results = [];
let i = 0;
const handleRequest = (url) => {
const req = fetch(url).then(res => {
console.log('当前并发: ' + requestsQueue);
const len = results.push(res);
if (len < urlCount && i + 1 < urlCount) {
requestsQueue.shift();
handleRequest(urls[++i])
} else if (len === urlCount) {
'function' === typeof callback && callback(results)
}
}).catch(e => {
results.push(e)
});
if (requestsQueue.push(req) < max) {
handleRequest(urls[++i])
}
};
handleRequest(urls[i])
}
// const urls = Array.from({ length: 10 }, (v, k) => k);
// const fetch = function (idx) {
// return new Promise(resolve => {
// console.log(`start request ${idx}`);
// const timeout = parseInt(Math.random() * 1e4);
// setTimeout(() => {
// console.log(`end request ${idx}`);
// resolve(idx)
// }, timeout)
// })
// };
// const max = 4;
// const callback = () => {
// console.log('run callback');
// };
// handleFetchQueue(urls, max, callback);
console