柯里化
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function curry(...args) { let argsList = [...args];
const fn = function (...args) { if (args.length) { argsList = [...argsList, ...args]; return fn; } return argsList.reduce((acc, val) => acc + val); } return fn; }
console.log(curry(1)(2)(3, 4)());
|
hardMAn
https://mp.weixin.qq.com/s/-hEjxY0yI6ZBTzAlc3xwAw
lru o(1)不使用 map,set
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| class DLinkedNode { constructor(key = 0, value = 0) { this.key = key; this.value = value; this.prev = null; this.next = null; } }
class LRUCache { constructor(capacity) { this.capacity = capacity; this.size = 0; this.cache = {}; this.head = new DLinkedNode(); this.tail = new DLinkedNode(); this.head.next = this.tail; this.tail.prev = this.head; }
get(key) { if (!this.cache[key]) { return -1; } const node = this.cache[key]; this.moveToHead(node); return node.value; }
put(key, value) { if (this.cache[key]) { const node = this.cache[key]; node.value = value; this.moveToHead(node); } else { const node = new DLinkedNode(key, value); this.cache[key] = node; this.addToHead(node); this.size++; if (this.size > this.capacity) { const removed = this.removeTail(); delete this.cache[removed.key]; this.size--; } } }
addToHead(node) { node.prev = this.head; node.next = this.head.next; this.head.next.prev = node; this.head.next = node; }
removeNode(node) { node.prev.next = node.next; node.next.prev = node.prev; }
moveToHead(node) { this.removeNode(node); this.addToHead(node); }
removeTail() { const node = this.tail.prev; this.removeNode(node); return node; } }
var LRUCache = function (capacity) { this.limit = capacity; this.cache = new Map(); }; LRUCache.prototype.get = function (key) { let tmp;
if (this.cache.has(key)) { tmp = this.cache.get(key);
this.cache.delete(key); this.cache.set(key, tmp); }
return tmp ?? -1; }; LRUCache.prototype.put = function (key, value) { if (this.cache.has(key)) { this.cache.delete(key); } this.cache.set(key, value);
if (this.cache.size > this.limit) { this.cache.delete(this.cache.keys().next().value); } };
|