Skip to content
This repository has been archived by the owner on Dec 6, 2022. It is now read-only.

Commit

Permalink
feat: immutable block and cached keys
Browse files Browse the repository at this point in the history
Fixes #10
  • Loading branch information
dignifiedquire committed Nov 3, 2016
1 parent 59ce8b6 commit b9f4187
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
26 changes: 24 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand All @@ -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)
})
}
}

Expand Down
12 changes: 6 additions & 6 deletions test/block.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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/
)
})
})

0 comments on commit b9f4187

Please sign in to comment.