From b9f4187171324ce7b22a409aaf268cdeeca53b1c Mon Sep 17 00:00:00 2001 From: Friedel Ziegelmayer Date: Thu, 3 Nov 2016 12:30:27 +0100 Subject: [PATCH] feat: immutable block and cached keys Fixes #10 --- src/index.js | 26 ++++++++++++++++++++++++-- test/block.spec.js | 12 ++++++------ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/src/index.js b/src/index.js index bbc0621..699c2db 100644 --- a/src/index.js +++ b/src/index.js @@ -14,7 +14,18 @@ function Block (data) { throw new Error('Block must be constructed with data') } - this.data = ensureBuffer(data) + this._cache = {} + + data = ensureBuffer(data) + + Object.defineProperty(this, 'data', { + get () { + return data + }, + set () { + throw new Error('Tried to change an immutable block') + } + }) this.key = (hashFunc, callback) => { if (typeof hashFunc === 'function') { @@ -26,7 +37,18 @@ function Block (data) { hashFunc = 'sha2-256' } - multihashing(this.data, hashFunc, callback) + if (this._cache[hashFunc]) { + setImmediate(() => { + callback(null, this._cache[hashFunc]) + }) + } + multihashing(this.data, hashFunc, (err, multihash) => { + if (err) { + return callback(err) + } + this._cache[hashFunc] = multihash + callback(null, multihash) + }) } } diff --git a/test/block.spec.js b/test/block.spec.js index 711076b..a66e457 100644 --- a/test/block.spec.js +++ b/test/block.spec.js @@ -62,13 +62,13 @@ describe('block', () => { }) }) - it.skip('block stays immutable', () => { - // it from the original implementation - // It doesn't stricly verify the immutability of the Block object + it('block stays immutable', () => { const block = new Block("Can't change this!") - let key = block.key() - key = new Buffer('new key') - expect(key.equals(block.key())).to.equal(false) + expect( + () => { block.data = 'fail' } + ).to.throw( + /immutable/ + ) }) })