-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHasher.mjs
55 lines (55 loc) · 1.83 KB
/
Hasher.mjs
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
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* @license MPL-2.0
* @author Alexander J. Vincent <[email protected]>
* @copyright © 2021-2022 Alexander J. Vincent
* @file
* This hashes multiple keys into a string. Unknown keys get new hash values if we need them.
*/
import { DefaultMap, DefaultWeakMap } from "./DefaultMap.mjs";
export default class KeyHasher {
/** @type {number} */
#hashCount = 0;
/** @type {WeakMap<object, string>} @constant */
#weakValueToHash = new DefaultWeakMap();
/** @type {Map<*, string>} @constant */
#strongValueToHash = new DefaultMap();
#incrementer = () => {
return (++this.#hashCount).toString(36);
};
#requireKey(key) {
if (Object(key) === key) {
return this.#weakValueToHash.getDefault(key, this.#incrementer);
}
return this.#strongValueToHash.getDefault(key, this.#incrementer);
}
constructor() {
if (new.target !== KeyHasher)
throw new Error("You cannot subclass KeyHasher!");
Object.freeze(this);
}
getHash(...args) {
const rv = args.map(arg => this.#requireKey(arg));
return rv.join(",");
}
getHashIfExists(...args) {
const values = [];
const result = args.every(arg => {
let rv;
if (Object(arg) === arg)
rv = this.#weakValueToHash.get(arg);
else
rv = this.#strongValueToHash.get(arg);
if (rv)
values.push(rv);
return rv;
});
return result ? values.join(",") : "";
}
}
Object.freeze(KeyHasher.prototype);
Object.freeze(KeyHasher);
//# sourceMappingURL=Hasher.mjs.map