linkedmap.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview A LinkedMap data structure that is accessed using key/value
  16. * pairs like an ordinary Map, but which guarantees a consistent iteration
  17. * order over its entries. The iteration order is either insertion order (the
  18. * default) or ordered from most recent to least recent use. By setting a fixed
  19. * size, the LRU version of the LinkedMap makes an effective object cache. This
  20. * data structure is similar to Java's LinkedHashMap.
  21. *
  22. * @author brenneman@google.com (Shawn Brenneman)
  23. */
  24. goog.provide('goog.structs.LinkedMap');
  25. goog.require('goog.structs.Map');
  26. /**
  27. * Class for a LinkedMap datastructure, which combines O(1) map access for
  28. * key/value pairs with a linked list for a consistent iteration order. Sample
  29. * usage:
  30. *
  31. * <pre>
  32. * var m = new LinkedMap();
  33. * m.set('param1', 'A');
  34. * m.set('param2', 'B');
  35. * m.set('param3', 'C');
  36. * alert(m.getKeys()); // param1, param2, param3
  37. *
  38. * var c = new LinkedMap(5, true);
  39. * for (var i = 0; i < 10; i++) {
  40. * c.set('entry' + i, false);
  41. * }
  42. * alert(c.getKeys()); // entry9, entry8, entry7, entry6, entry5
  43. *
  44. * c.set('entry5', true);
  45. * c.set('entry1', false);
  46. * alert(c.getKeys()); // entry1, entry5, entry9, entry8, entry7
  47. * </pre>
  48. *
  49. * @param {number=} opt_maxCount The maximum number of objects to store in the
  50. * LinkedMap. If unspecified or 0, there is no maximum.
  51. * @param {boolean=} opt_cache When set, the LinkedMap stores items in order
  52. * from most recently used to least recently used, instead of insertion
  53. * order.
  54. * @param {function(string, VALUE)=} opt_evictionCallback Called with the
  55. * removed stringified key as the first argument and value as the second
  56. * argument after the key was evicted from the LRU because the max count
  57. * was reached.
  58. * @constructor
  59. * @template KEY, VALUE
  60. */
  61. goog.structs.LinkedMap = function(
  62. opt_maxCount, opt_cache, opt_evictionCallback) {
  63. /**
  64. * The maximum number of entries to allow, or null if there is no limit.
  65. * @private {?number}
  66. */
  67. this.maxCount_ = opt_maxCount || null;
  68. /** @private @const {boolean} */
  69. this.cache_ = !!opt_cache;
  70. /** @private {function(string, VALUE)|undefined} */
  71. this.evictionCallback_ = opt_evictionCallback;
  72. /**
  73. * @private @const {!goog.structs.Map<string,
  74. * goog.structs.LinkedMap.Node_<string, VALUE>>}
  75. */
  76. this.map_ = new goog.structs.Map();
  77. this.head_ = new goog.structs.LinkedMap.Node_('', undefined);
  78. this.head_.next = this.head_.prev = this.head_;
  79. };
  80. /**
  81. * Finds a node and updates it to be the most recently used.
  82. * @param {string} key The key of the node.
  83. * @return {goog.structs.LinkedMap.Node_<string, VALUE>} The node or null if not
  84. * found.
  85. * @private
  86. */
  87. goog.structs.LinkedMap.prototype.findAndMoveToTop_ = function(key) {
  88. var node = this.map_.get(key);
  89. if (node) {
  90. if (this.cache_) {
  91. node.remove();
  92. this.insert_(node);
  93. }
  94. }
  95. return node;
  96. };
  97. /**
  98. * Retrieves the value for a given key. If this is a caching LinkedMap, the
  99. * entry will become the most recently used.
  100. * @param {string} key The key to retrieve the value for.
  101. * @param {VALUE=} opt_val A default value that will be returned if the key is
  102. * not found, defaults to undefined.
  103. * @return {VALUE} The retrieved value.
  104. */
  105. goog.structs.LinkedMap.prototype.get = function(key, opt_val) {
  106. var node = this.findAndMoveToTop_(key);
  107. return node ? node.value : opt_val;
  108. };
  109. /**
  110. * Retrieves the value for a given key without updating the entry to be the
  111. * most recently used.
  112. * @param {string} key The key to retrieve the value for.
  113. * @param {VALUE=} opt_val A default value that will be returned if the key is
  114. * not found.
  115. * @return {VALUE} The retrieved value.
  116. */
  117. goog.structs.LinkedMap.prototype.peekValue = function(key, opt_val) {
  118. var node = this.map_.get(key);
  119. return node ? node.value : opt_val;
  120. };
  121. /**
  122. * Sets a value for a given key. If this is a caching LinkedMap, this entry
  123. * will become the most recently used.
  124. * @param {string} key Key with which the specified value is to be associated.
  125. * @param {VALUE} value Value to be associated with the specified key.
  126. */
  127. goog.structs.LinkedMap.prototype.set = function(key, value) {
  128. var node = this.findAndMoveToTop_(key);
  129. if (node) {
  130. node.value = value;
  131. } else {
  132. node = new goog.structs.LinkedMap.Node_(key, value);
  133. this.map_.set(key, node);
  134. this.insert_(node);
  135. }
  136. };
  137. /**
  138. * Returns the value of the first node without making any modifications.
  139. * @return {VALUE} The value of the first node or undefined if the map is empty.
  140. */
  141. goog.structs.LinkedMap.prototype.peek = function() {
  142. return this.head_.next.value;
  143. };
  144. /**
  145. * Returns the value of the last node without making any modifications.
  146. * @return {VALUE} The value of the last node or undefined if the map is empty.
  147. */
  148. goog.structs.LinkedMap.prototype.peekLast = function() {
  149. return this.head_.prev.value;
  150. };
  151. /**
  152. * Removes the first node from the list and returns its value.
  153. * @return {VALUE} The value of the popped node, or undefined if the map was
  154. * empty.
  155. */
  156. goog.structs.LinkedMap.prototype.shift = function() {
  157. return this.popNode_(this.head_.next);
  158. };
  159. /**
  160. * Removes the last node from the list and returns its value.
  161. * @return {VALUE} The value of the popped node, or undefined if the map was
  162. * empty.
  163. */
  164. goog.structs.LinkedMap.prototype.pop = function() {
  165. return this.popNode_(this.head_.prev);
  166. };
  167. /**
  168. * Removes a value from the LinkedMap based on its key.
  169. * @param {string} key The key to remove.
  170. * @return {boolean} True if the entry was removed, false if the key was not
  171. * found.
  172. */
  173. goog.structs.LinkedMap.prototype.remove = function(key) {
  174. var node = this.map_.get(key);
  175. if (node) {
  176. this.removeNode(node);
  177. return true;
  178. }
  179. return false;
  180. };
  181. /**
  182. * Removes a node from the {@code LinkedMap}. It can be overridden to do
  183. * further cleanup such as disposing of the node value.
  184. * @param {!goog.structs.LinkedMap.Node_<string, VALUE>} node The node to
  185. * remove.
  186. * @protected
  187. */
  188. goog.structs.LinkedMap.prototype.removeNode = function(node) {
  189. node.remove();
  190. this.map_.remove(node.key);
  191. };
  192. /**
  193. * @return {number} The number of items currently in the LinkedMap. Sub classes
  194. * may override this to change how items are counted (e.g. to introduce
  195. * per item weight). Truncation will always proceed as long as the count
  196. * returned from this method is higher than the max count for this map.
  197. */
  198. goog.structs.LinkedMap.prototype.getCount = function() {
  199. return this.map_.getCount();
  200. };
  201. /**
  202. * @return {boolean} True if the cache is empty, false if it contains any items.
  203. */
  204. goog.structs.LinkedMap.prototype.isEmpty = function() {
  205. return this.map_.isEmpty();
  206. };
  207. /**
  208. * Sets a callback that fires when an entry is evicted because max entry
  209. * count is reached. The callback is called with the removed stringified key
  210. * as the first argument and value as the second argument after the key was
  211. * evicted from the LRU because the max count was reached.
  212. * @param {function(string, VALUE)} evictionCallback
  213. */
  214. goog.structs.LinkedMap.prototype.setEvictionCallback = function(
  215. evictionCallback) {
  216. this.evictionCallback_ = evictionCallback;
  217. };
  218. /**
  219. * Sets the maximum number of entries allowed in this object, truncating any
  220. * excess objects if necessary.
  221. * @param {number} maxCount The new maximum number of entries to allow.
  222. */
  223. goog.structs.LinkedMap.prototype.setMaxCount = function(maxCount) {
  224. this.maxCount_ = maxCount || null;
  225. if (this.maxCount_ != null) {
  226. this.truncate_(this.maxCount_);
  227. }
  228. };
  229. /**
  230. * @return {!Array<string>} The list of the keys in the appropriate order for
  231. * this LinkedMap.
  232. */
  233. goog.structs.LinkedMap.prototype.getKeys = function() {
  234. return this.map(function(val, key) { return key; });
  235. };
  236. /**
  237. * @return {!Array<VALUE>} The list of the values in the appropriate order for
  238. * this LinkedMap.
  239. */
  240. goog.structs.LinkedMap.prototype.getValues = function() {
  241. return this.map(function(val, key) { return val; });
  242. };
  243. /**
  244. * Tests whether a provided value is currently in the LinkedMap. This does not
  245. * affect item ordering in cache-style LinkedMaps.
  246. * @param {VALUE} value The value to check for.
  247. * @return {boolean} Whether the value is in the LinkedMap.
  248. */
  249. goog.structs.LinkedMap.prototype.contains = function(value) {
  250. return this.some(function(el) { return el == value; });
  251. };
  252. /**
  253. * Tests whether a provided key is currently in the LinkedMap. This does not
  254. * affect item ordering in cache-style LinkedMaps.
  255. * @param {string} key The key to check for.
  256. * @return {boolean} Whether the key is in the LinkedMap.
  257. */
  258. goog.structs.LinkedMap.prototype.containsKey = function(key) {
  259. return this.map_.containsKey(key);
  260. };
  261. /**
  262. * Removes all entries in this object.
  263. */
  264. goog.structs.LinkedMap.prototype.clear = function() {
  265. this.truncate_(0);
  266. };
  267. /**
  268. * Calls a function on each item in the LinkedMap.
  269. *
  270. * @see goog.structs.forEach
  271. * @param {function(this:T, VALUE, KEY, goog.structs.LinkedMap<KEY, VALUE>)} f
  272. * @param {T=} opt_obj The value of "this" inside f.
  273. * @template T
  274. */
  275. goog.structs.LinkedMap.prototype.forEach = function(f, opt_obj) {
  276. for (var n = this.head_.next; n != this.head_; n = n.next) {
  277. f.call(opt_obj, n.value, n.key, this);
  278. }
  279. };
  280. /**
  281. * Calls a function on each item in the LinkedMap and returns the results of
  282. * those calls in an array.
  283. *
  284. * @see goog.structs.map
  285. * @param {function(this:T, VALUE, KEY,
  286. * goog.structs.LinkedMap<KEY, VALUE>): RESULT} f
  287. * The function to call for each item. The function takes
  288. * three arguments: the value, the key, and the LinkedMap.
  289. * @param {T=} opt_obj The object context to use as "this" for the
  290. * function.
  291. * @return {!Array<RESULT>} The results of the function calls for each item in
  292. * the LinkedMap.
  293. * @template T,RESULT
  294. */
  295. goog.structs.LinkedMap.prototype.map = function(f, opt_obj) {
  296. var rv = [];
  297. for (var n = this.head_.next; n != this.head_; n = n.next) {
  298. rv.push(f.call(opt_obj, n.value, n.key, this));
  299. }
  300. return rv;
  301. };
  302. /**
  303. * Calls a function on each item in the LinkedMap and returns true if any of
  304. * those function calls returns a true-like value.
  305. *
  306. * @see goog.structs.some
  307. * @param {function(this:T, VALUE, KEY,
  308. * goog.structs.LinkedMap<KEY, VALUE>):boolean} f
  309. * The function to call for each item. The function takes
  310. * three arguments: the value, the key, and the LinkedMap, and returns a
  311. * boolean.
  312. * @param {T=} opt_obj The object context to use as "this" for the
  313. * function.
  314. * @return {boolean} Whether f evaluates to true for at least one item in the
  315. * LinkedMap.
  316. * @template T
  317. */
  318. goog.structs.LinkedMap.prototype.some = function(f, opt_obj) {
  319. for (var n = this.head_.next; n != this.head_; n = n.next) {
  320. if (f.call(opt_obj, n.value, n.key, this)) {
  321. return true;
  322. }
  323. }
  324. return false;
  325. };
  326. /**
  327. * Calls a function on each item in the LinkedMap and returns true only if every
  328. * function call returns a true-like value.
  329. *
  330. * @see goog.structs.some
  331. * @param {function(this:T, VALUE, KEY,
  332. * goog.structs.LinkedMap<KEY, VALUE>):boolean} f
  333. * The function to call for each item. The function takes
  334. * three arguments: the value, the key, and the Cache, and returns a
  335. * boolean.
  336. * @param {T=} opt_obj The object context to use as "this" for the
  337. * function.
  338. * @return {boolean} Whether f evaluates to true for every item in the Cache.
  339. * @template T
  340. */
  341. goog.structs.LinkedMap.prototype.every = function(f, opt_obj) {
  342. for (var n = this.head_.next; n != this.head_; n = n.next) {
  343. if (!f.call(opt_obj, n.value, n.key, this)) {
  344. return false;
  345. }
  346. }
  347. return true;
  348. };
  349. /**
  350. * Appends a node to the list. LinkedMap in cache mode adds new nodes to
  351. * the head of the list, otherwise they are appended to the tail. If there is a
  352. * maximum size, the list will be truncated if necessary.
  353. *
  354. * @param {goog.structs.LinkedMap.Node_<string, VALUE>} node The item to insert.
  355. * @private
  356. */
  357. goog.structs.LinkedMap.prototype.insert_ = function(node) {
  358. if (this.cache_) {
  359. node.next = this.head_.next;
  360. node.prev = this.head_;
  361. this.head_.next = node;
  362. node.next.prev = node;
  363. } else {
  364. node.prev = this.head_.prev;
  365. node.next = this.head_;
  366. this.head_.prev = node;
  367. node.prev.next = node;
  368. }
  369. if (this.maxCount_ != null) {
  370. this.truncate_(this.maxCount_);
  371. }
  372. };
  373. /**
  374. * Removes elements from the LinkedMap if the given count has been exceeded.
  375. * In cache mode removes nodes from the tail of the list. Otherwise removes
  376. * nodes from the head.
  377. * @param {number} count Number of elements to keep.
  378. * @private
  379. */
  380. goog.structs.LinkedMap.prototype.truncate_ = function(count) {
  381. while (this.getCount() > count) {
  382. var toRemove = this.cache_ ? this.head_.prev : this.head_.next;
  383. this.removeNode(toRemove);
  384. if (this.evictionCallback_) {
  385. this.evictionCallback_(toRemove.key, toRemove.value);
  386. }
  387. }
  388. };
  389. /**
  390. * Removes the node from the LinkedMap if it is not the head, and returns
  391. * the node's value.
  392. * @param {!goog.structs.LinkedMap.Node_<string, VALUE>} node The item to
  393. * remove.
  394. * @return {VALUE} The value of the popped node.
  395. * @private
  396. */
  397. goog.structs.LinkedMap.prototype.popNode_ = function(node) {
  398. if (this.head_ != node) {
  399. this.removeNode(node);
  400. }
  401. return node.value;
  402. };
  403. /**
  404. * Internal class for a doubly-linked list node containing a key/value pair.
  405. * @param {KEY} key The key.
  406. * @param {VALUE} value The value.
  407. * @constructor
  408. * @template KEY, VALUE
  409. * @private
  410. */
  411. goog.structs.LinkedMap.Node_ = function(key, value) {
  412. /** @type {KEY} */
  413. this.key = key;
  414. /** @type {VALUE} */
  415. this.value = value;
  416. };
  417. /**
  418. * The next node in the list.
  419. * @type {!goog.structs.LinkedMap.Node_<KEY, VALUE>}
  420. */
  421. goog.structs.LinkedMap.Node_.prototype.next;
  422. /**
  423. * The previous node in the list.
  424. * @type {!goog.structs.LinkedMap.Node_<KEY, VALUE>}
  425. */
  426. goog.structs.LinkedMap.Node_.prototype.prev;
  427. /**
  428. * Causes this node to remove itself from the list.
  429. */
  430. goog.structs.LinkedMap.Node_.prototype.remove = function() {
  431. this.prev.next = this.next;
  432. this.next.prev = this.prev;
  433. delete this.prev;
  434. delete this.next;
  435. };