马宇豪
2024-07-16 f591c27b57e2418c9495bc02ae8cfff84d35bc18
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
/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Tobias Koppers @sokra
*/
 
"use strict";
 
const createHash = require("../util/createHash");
 
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {typeof import("../util/Hash")} HashConstructor */
 
/**
 * @typedef {Object} HashableObject
 * @property {function(Hash): void} updateHash
 */
 
class LazyHashedEtag {
    /**
     * @param {HashableObject} obj object with updateHash method
     * @param {string | HashConstructor} hashFunction the hash function to use
     */
    constructor(obj, hashFunction = "md4") {
        this._obj = obj;
        this._hash = undefined;
        this._hashFunction = hashFunction;
    }
 
    /**
     * @returns {string} hash of object
     */
    toString() {
        if (this._hash === undefined) {
            const hash = createHash(this._hashFunction);
            this._obj.updateHash(hash);
            this._hash = /** @type {string} */ (hash.digest("base64"));
        }
        return this._hash;
    }
}
 
/** @type {Map<string | HashConstructor, WeakMap<HashableObject, LazyHashedEtag>>} */
const mapStrings = new Map();
 
/** @type {WeakMap<HashConstructor, WeakMap<HashableObject, LazyHashedEtag>>} */
const mapObjects = new WeakMap();
 
/**
 * @param {HashableObject} obj object with updateHash method
 * @param {string | HashConstructor} hashFunction the hash function to use
 * @returns {LazyHashedEtag} etag
 */
const getter = (obj, hashFunction = "md4") => {
    let innerMap;
    if (typeof hashFunction === "string") {
        innerMap = mapStrings.get(hashFunction);
        if (innerMap === undefined) {
            const newHash = new LazyHashedEtag(obj, hashFunction);
            innerMap = new WeakMap();
            innerMap.set(obj, newHash);
            mapStrings.set(hashFunction, innerMap);
            return newHash;
        }
    } else {
        innerMap = mapObjects.get(hashFunction);
        if (innerMap === undefined) {
            const newHash = new LazyHashedEtag(obj, hashFunction);
            innerMap = new WeakMap();
            innerMap.set(obj, newHash);
            mapObjects.set(hashFunction, innerMap);
            return newHash;
        }
    }
    const hash = innerMap.get(obj);
    if (hash !== undefined) return hash;
    const newHash = new LazyHashedEtag(obj, hashFunction);
    innerMap.set(obj, newHash);
    return newHash;
};
 
module.exports = getter;