Skip to content

Commit

Permalink
FIFO先进先出队列缓存
Browse files Browse the repository at this point in the history
  • Loading branch information
cslc-ubm committed Dec 10, 2020
1 parent 5fe8d44 commit d11228a
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions FIFO先进先出队列缓存.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// 先进先出缓存函数
function memory(f, maxSize = 10) {
let cache = []

return (...args) => {
let hash = args.join(',')

let item = cache.find((x) => x.hash === hash)
if (item) {
return item.value
}

const result = f(...args)
cache.push({
hash,
value: result
})

if (cache.length > maxSize) {
cache.shift()
}
return result
}
}

function fibo(n) {
if (n === 1 || n === 2) {
return 1
}
// 此处使用缓存函数
return mfib(n - 1) + mfib(n - 2)
}

let mfib = memory(fibo)
console.log(mfib(45))

0 comments on commit d11228a

Please sign in to comment.