From 3770b30040ded9199dd5c948e3379a0efce9774b Mon Sep 17 00:00:00 2001 From: yige Date: Mon, 25 May 2020 22:27:39 +0800 Subject: [PATCH] =?UTF-8?q?add:=20LRU=E7=BC=93=E5=AD=98=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ src/array/lru-cache.js | 21 +++++++++++++++++++++ test/array/lru-cache.test.js | 15 +++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 src/array/lru-cache.js create mode 100644 test/array/lru-cache.test.js diff --git a/README.md b/README.md index 3a086b2..ba7864c 100644 --- a/README.md +++ b/README.md @@ -343,6 +343,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 860. 柠檬水找零 - LintCode 1509. 柠檬水找零 +- [LRU缓存机制](src/array/lru-cache.js) + + - LeetCode 146. LRU缓存机制 + - LintCode 134. LRU缓存策略 + ## 栈 - [最大矩阵](src/stack/maximal-rectangle.js) diff --git a/src/array/lru-cache.js b/src/array/lru-cache.js new file mode 100644 index 0000000..4c5d1d0 --- /dev/null +++ b/src/array/lru-cache.js @@ -0,0 +1,21 @@ +export default class LRUCache { + constructor (capacity) { + this.max = capacity; this.map = new Map() + } + + get (key) { + const value = this.map.get(key) + if (value !== undefined) { + this.map.delete(key) + this.map.set(key, value) + return value + } + return -1 + } + + put (key, value) { + this.map.delete(key) + this.map.set(key, value) + if (this.map.size > this.max) this.map.delete(this.map.keys().next().value) + } +} diff --git a/test/array/lru-cache.test.js b/test/array/lru-cache.test.js new file mode 100644 index 0000000..bed276e --- /dev/null +++ b/test/array/lru-cache.test.js @@ -0,0 +1,15 @@ +import LRUCache from '../../src/array/lru-cache' + +test('LRU缓存机制', () => { + const cache = new LRUCache(2 /* 缓存容量 */) + + cache.put(1, 1) + cache.put(2, 2) + expect(cache.get(1)).toBe(1) // 返回 1 + cache.put(3, 3) // 该操作会使得密钥 2 作废 + expect(cache.get(2)).toBe(-1) // 返回 -1 (未找到) + cache.put(4, 4) // 该操作会使得密钥 1 作废 + expect(cache.get(1)).toBe(-1) // 返回 -1 (未找到) + expect(cache.get(3)).toBe(3) // 返回 3 + expect(cache.get(4)).toBe(4) // 返回 4 +})