| 1 | /** |
| 2 | * A specialized Map class that provides consistent data storage by performing deep cloning of values. |
| 3 | * |
| 4 | * @template K, V |
| 5 | * @extends Map<K, V> |
| 6 | */ |
| 7 | export class StructuredCloneMap extends Map { |
| 8 | /** |
| 9 | * Constructs a new StructuredCloneMap. |
| 10 | * @param {object} options - Options for the map |
| 11 | * @param {boolean} options.cloneOnGet - Whether to clone the value when getting it from the map |
| 12 | * @param {boolean} options.cloneOnSet - Whether to clone the value when setting it in the map |
| 13 | */ |
| 14 | constructor({ cloneOnGet, cloneOnSet } = { cloneOnGet: true, cloneOnSet: true }) { |
| 15 | super(); |
| 16 | this.cloneOnGet = cloneOnGet; |
| 17 | this.cloneOnSet = cloneOnSet; |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated. |
| 22 | * |
| 23 | * The set value will always be a deep clone of the provided value to provide consistent data storage. |
| 24 | * |
| 25 | * @param {K} key - The key to set |
| 26 | * @param {V} value - The value to set |
| 27 | * @returns {this} The updated map |
| 28 | */ |
| 29 | set(key, value) { |
| 30 | if (!this.cloneOnSet) { |
| 31 | return super.set(key, value); |
| 32 | } |
| 33 | |
| 34 | const clonedValue = structuredClone(value); |
| 35 | super.set(key, clonedValue); |
| 36 | return this; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Returns a specified element from the Map object. |
| 41 | * If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map. |
| 42 | * |
| 43 | * The returned value will always be a deep clone of the cached value. |
| 44 | * |
| 45 | * @param {K} key - The key to get the value for |
| 46 | * @returns {V | undefined} Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. |
| 47 | */ |
| 48 | get(key) { |
| 49 | if (!this.cloneOnGet) { |
| 50 | return super.get(key); |
| 51 | } |
| 52 | |
| 53 | const value = super.get(key); |
| 54 | return structuredClone(value); |
| 55 | } |
| 56 | } |