使用 TTL (NodeJS) 保存号码

Save number with TTL (NodeJS)

我看到很多使用密钥的 TTL NodeJS 包,但是我不能使用密钥。我想做这样的事情:

const responseTimes = []

// TODO: Implement a function to delete item in array at end of TTL

// function that runs
doSomething().then(response => {
  responseTimes.push({ duration: response.duration, TTL: thirtySeconds })
})

// function that gets 30s average
const getAverage = () => {
  return Math.AVG(responseTimes.map(time => time.duration))
}

TTL 在此上下文中意味着 responseTime 对象将在这种情况下的 30 秒 TTL 后删除。

如何完成删除指定 TTL 末尾的数组对象的 TODO?

最简单的方法是不使用 TTL 实现任何类型的缓存,而是将时间戳与 responseTime 一起保存。然后,在调用 getAverage 时,忽略(甚至删除)时间戳超过 30 秒前的所有响应时间。

const responseTimes = []

// function that runs
doSomething().then(response => {
    responseTimes.push({ duration: response.duration, time: Date.now() })
})

// function that gets 30s average
const getAverage = () => {
    return Math.AVG(responseTimes
        .filter(entry => entry.time < (Date.now() - 30000))
        .map(time => time.duration)
    );
}

(此代码仅忽略且不删除早于 30 秒的响应时间 - 如果随着时间的推移,您保存了许多响应时间,那么请执行删除旧响应时间的代码,否则内存将 运行 随着时间的推移,对 getAverage 的调用将花费很长时间;-))