From 3f3e0534cc742c76b1bf356c8cdeef2b18198f91 Mon Sep 17 00:00:00 2001 From: Alexey Date: Thu, 18 Jul 2019 00:25:16 +0300 Subject: [PATCH] merkle tree update - getIndexByElement --- lib/MerkleTree.js | 10 ++++++++++ test/MerkleTreeWithHistory.test.js | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/MerkleTree.js b/lib/MerkleTree.js index f0e6ffa..6c7cbac 100644 --- a/lib/MerkleTree.js +++ b/lib/MerkleTree.js @@ -179,6 +179,16 @@ class MerkleTree { current_index = Math.floor(current_index / 2) } } + + getIndexByElement(element) { + for(let i = this.totalElements - 1; i >= 0; i--) { + const elementFromTree = this.storage.get(MerkleTree.index_to_key(this.prefix, 0, i)) + if (elementFromTree === element) { + return i + } + } + return false + } } module.exports = MerkleTree diff --git a/test/MerkleTreeWithHistory.test.js b/test/MerkleTreeWithHistory.test.js index e5241a0..63a5cfb 100644 --- a/test/MerkleTreeWithHistory.test.js +++ b/test/MerkleTreeWithHistory.test.js @@ -102,6 +102,27 @@ contract('MerkleTreeWithHistory', accounts => { } }) + it('should find an element', async () => { + const elements = [12, 13, 14, 15, 16, 17, 18, 19, 20] + for(const [, el] of Object.entries(elements)) { + await tree.insert(el) + } + let index = tree.getIndexByElement(13) + index.should.be.equal(1) + + index = tree.getIndexByElement(19) + index.should.be.equal(7) + + index = tree.getIndexByElement(12) + index.should.be.equal(0) + + index = tree.getIndexByElement(20) + index.should.be.equal(8) + + index = tree.getIndexByElement(42) + index.should.be.equal(false) + }) + it('creation even elements count', async () => { const elements = [12, 13, 14, 15, 16, 17] for(const [, el] of Object.entries(elements)) {