1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 | const createHash = require("../util/createHash");
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | class LazyHashedEtag {
|
19 | |
20 |
|
21 |
|
22 |
|
23 | constructor(obj, hashFunction = "md4") {
|
24 | this._obj = obj;
|
25 | this._hash = undefined;
|
26 | this._hashFunction = hashFunction;
|
27 | }
|
28 |
|
29 | |
30 |
|
31 |
|
32 | toString() {
|
33 | if (this._hash === undefined) {
|
34 | const hash = createHash(this._hashFunction);
|
35 | this._obj.updateHash(hash);
|
36 | this._hash = (hash.digest("base64"));
|
37 | }
|
38 | return this._hash;
|
39 | }
|
40 | }
|
41 |
|
42 |
|
43 | const mapStrings = new Map();
|
44 |
|
45 |
|
46 | const mapObjects = new WeakMap();
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | const getter = (obj, hashFunction = "md4") => {
|
54 | let innerMap;
|
55 | if (typeof hashFunction === "string") {
|
56 | innerMap = mapStrings.get(hashFunction);
|
57 | if (innerMap === undefined) {
|
58 | const newHash = new LazyHashedEtag(obj, hashFunction);
|
59 | innerMap = new WeakMap();
|
60 | innerMap.set(obj, newHash);
|
61 | mapStrings.set(hashFunction, innerMap);
|
62 | return newHash;
|
63 | }
|
64 | } else {
|
65 | innerMap = mapObjects.get(hashFunction);
|
66 | if (innerMap === undefined) {
|
67 | const newHash = new LazyHashedEtag(obj, hashFunction);
|
68 | innerMap = new WeakMap();
|
69 | innerMap.set(obj, newHash);
|
70 | mapObjects.set(hashFunction, innerMap);
|
71 | return newHash;
|
72 | }
|
73 | }
|
74 | const hash = innerMap.get(obj);
|
75 | if (hash !== undefined) return hash;
|
76 | const newHash = new LazyHashedEtag(obj, hashFunction);
|
77 | innerMap.set(obj, newHash);
|
78 | return newHash;
|
79 | };
|
80 |
|
81 | module.exports = getter;
|