SOURCE

function ItemCache(data, timeout) {
    this.data = data
    this.timeout = timeout
    this.cacheTime = new Date().getTime()
}

const ExpriesCache = {}
ExpriesCache.cacheMap = new Map()

ExpriesCache.isDue = function (name) {
    const data = ExpriesCache.cacheMap.get(name)

    if (!data) return true

    const currentTime = new Date().getTime()
    const overTime = (currentTime - data.cacheTime) / 1000
    if (overTime > data.timeout) {
        ExpriesCache.cacheMap.delete(name)
        return true
    }

    return false
}

ExpriesCache.delete = function (name) {
    return ExpriesCache.cacheMap.delete(name)
}

ExpriesCache.get = function (name) {
    const isDataOverTiem = ExpriesCache.isOverTime(name)
    return isDataOverTiem ? null : ExpriesCache.cacheMap.get(name).data
}

ExpriesCache.set = function (name, data, timeout = 600) {
    const itemCache = new ItemCache(data, timeout)
    ExpriesCache.cacheMap.set(name, itemCache)
}


function generateKey(name, ...args) {
    const params = Array.from(args).join(',')

    try {
        return `${name}:${params}`
    } catch (err) {
        return new Error('Fail to generate key from name and argument')
    }
}

function getNumber(param) {
    const key = generateKey('geyNumber', param)
    let promise = ExpriesCache.get(key);
    if (!promise) {
        promise = fetch(`http://numbersapi.com/${param}`)
            .then(res => res.text())
            .catch(err => {
                ExpriesCache.delete(key)
                return Promise.reject(error)
            })
        ExpriesCache.set(key, promise, 10)
    }
    return promise
}

getNumber(1).then(res => console.log(res))
getNumber(2).then(res => console.log(res))


console 命令行工具 X clear

                    
>
console