diff --git a/README.md b/README.md index ef29171..45b5229 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,9 @@ export class LRUMap { // Returns an object suitable for JSON encoding toJSON() : Array<{key :K, value :V}>; + // Returns an LRU Map from JSON encoding + fromJSON(json :Array<{key :K, value :V}>) : LRUMap; + // Returns a human-readable text representation toString() : string; } diff --git a/lru.d.ts b/lru.d.ts index 8672c72..d0df79f 100644 --- a/lru.d.ts +++ b/lru.d.ts @@ -72,6 +72,9 @@ export class LRUMap { // Returns an object suitable for JSON encoding toJSON() : Array<{key :K, value :V}>; + // Returns an LRU Map from JSON encoding + fromJSON(json :Array<{key :K, value :V}>) : LRUMap; + // Returns a human-readable text representation toString() : string; } diff --git a/lru.js b/lru.js index d2657ee..8d87626 100644 --- a/lru.js +++ b/lru.js @@ -245,6 +245,13 @@ class LRUMap { return s; } + /** Static method to create an LRUMap instance from a JSON export of a previous LRUMap */ + static fromJSON(json) { + return new LRUMap(json.map(it => { + return [it.key, it.value] + })) + } + /** Returns a String representation */ toString() { var s = '', entry = this.oldest; diff --git a/package.json b/package.json index f2e3bce..700cf5f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lru_map", - "version": "0.4.1", + "version": "0.4.2", "description": "Finite key-value map using the Least Recently Used (LRU) algorithm where the most recently used objects are keept in the map while less recently used items are evicted to make room for new ones.", "main": "dist/lru.js", "types": "lru.d.ts", diff --git a/test.js b/test.js index a201d97..562117d 100644 --- a/test.js +++ b/test.js @@ -287,6 +287,19 @@ toJSON() { ]); }, +fromJSON() { + let c = new LRUMap(4, [ + ['adam', 29], + ['john', 26], + ['angela', 24], + ['bob', 48], + ]); + let json = c.toJSON(); + let n = LRUMap.fromJSON(json); + assert(n.size == 4); + assert.deepEqual(n, c); + assert.deepEqual(n.entries(), c.entries()); +}, }; // tests