fix: remove toString side effect that breaks deep equals (#142)

Makes the cached string cid property non-enumerable so deep equals
still works even after a peer id has been stringifed.

Fixes #141
This commit is contained in:
Alex Potsides 2021-03-29 11:53:11 +01:00 committed by GitHub
parent 5468ee0877
commit eeb53305c8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 1 deletions

View File

@ -137,7 +137,11 @@ class PeerId {
toString () { toString () {
if (!this._idCIDString) { if (!this._idCIDString) {
const cid = new CID(1, 'libp2p-key', this.id, 'base32') const cid = new CID(1, 'libp2p-key', this.id, 'base32')
this._idCIDString = cid.toBaseEncodedString('base32')
Object.defineProperty(this, '_idCIDString', {
value: cid.toBaseEncodedString('base32'),
enumerable: false
})
} }
return this._idCIDString return this._idCIDString
} }

View File

@ -309,6 +309,18 @@ describe('PeerId', () => {
expect(peerId.isValid()).to.equal(false) expect(peerId.isValid()).to.equal(false)
}) })
it('keys are equal after one is stringified', async () => {
const peerId = await PeerId.create(testOpts)
const peerId1 = PeerId.createFromB58String(peerId.toB58String())
const peerId2 = PeerId.createFromB58String(peerId.toB58String())
expect(peerId1).to.deep.equal(peerId2)
peerId1.toString()
expect(peerId1).to.deep.equal(peerId2)
})
describe('returns error via cb instead of crashing', () => { describe('returns error via cb instead of crashing', () => {
const garbage = [ const garbage = [
uint8ArrayFromString('00010203040506070809', 'base16'), uint8ArrayFromString('00010203040506070809', 'base16'),