BFE.devでのAI解答例 - JavaScript コーディング問題
17. DOM element storeを作る
以下はMapを利用しないNodeStoreの実装例です。
class NodeStore { constructor() { this.store = {}; } set(node, value) { const id = this.getId(node); if (!id) { return; } this.store[id] = value; } get(node) { const id = this.getId(node); if (!id) { return undefined; } return this.store[id]; } has(node) { const id = this.getId(node); return !!id; } getId(node) { if (node.nodeType !== Node.ELEMENT_NODE) { return false; } if (!node.hasAttribute('data-node-store-id')) { node.setAttribute('data-node-store-id', String(Date.now())); } return node.getAttribute('data-node-store-id'); }}
この実装では、DOM要素にランダムなIDを追加することで、ノードを識別します。 set
、 get
、およびhas
メソッドを提供し、 set
メソッドでは、値をストア内のIDに対応するエントリに設定します。 get
メソッドはIDに対応するエントリから値を返し、 has
メソッドはノードがストア内に存在するかどうかを確認します。
この実装は、データの追加、取得、および存在確認がすべてO(1)で実行できるため、時間の面でも空間の面でも効率的です。