Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add a fromJSON static method #41

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ export class LRUMap<K,V> {
// 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<K,V>;

// Returns a human-readable text representation
toString() : string;
}
Expand Down
3 changes: 3 additions & 0 deletions lru.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ export class LRUMap<K,V> {
// 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<K,V>;

// Returns a human-readable text representation
toString() : string;
}
Expand Down
7 changes: 7 additions & 0 deletions lru.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
13 changes: 13 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down