Skip to content

Commit

Permalink
fix: make peerid optional in peerid.equals (#2335)
Browse files Browse the repository at this point in the history
This makes the code a bit more flexible, for example when taking
action based on an optional peerid having been passed to a function
when an existing peer id is known.
  • Loading branch information
achingbrain committed Dec 28, 2023
1 parent 5d1f68e commit f1c1167
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/interface/src/peer-id/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ interface BasePeerId {
toString(): string
toCID(): CID
toBytes(): Uint8Array
equals(other: PeerId | Uint8Array | string): boolean
equals(other?: PeerId | Uint8Array | string): boolean
}

export interface RSAPeerId extends BasePeerId {
Expand Down
6 changes: 5 additions & 1 deletion packages/peer-id/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,11 @@ class PeerIdImpl {
/**
* Checks the equality of `this` peer against a given PeerId
*/
equals (id: PeerId | Uint8Array | string): boolean {
equals (id?: PeerId | Uint8Array | string): boolean {
if (id == null) {
return false
}

if (id instanceof Uint8Array) {
return uint8ArrayEquals(this.multihash.bytes, id)
} else if (typeof id === 'string') {
Expand Down
12 changes: 12 additions & 0 deletions packages/peer-id/test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ describe('PeerId', () => {
expect(id.equals(peerIdFromBytes(buf))).to.be.true()
})

it('equals nothing', async () => {
const buf = uint8ArrayFromString('12D3KooWbtp1AcgweFSArD7dbKWYpAr8MZR1tofwNwLFLjeNGLWa', 'base58btc')
const id = peerIdFromBytes(buf)
expect(id.equals()).to.be.false()
})

it('equals undefined', async () => {
const buf = uint8ArrayFromString('12D3KooWbtp1AcgweFSArD7dbKWYpAr8MZR1tofwNwLFLjeNGLWa', 'base58btc')
const id = peerIdFromBytes(buf)
expect(id.equals(undefined)).to.be.false()
})

it('parses a PeerId as Ed25519', async () => {
const id = peerIdFromString('12D3KooWbtp1AcgweFSArD7dbKWYpAr8MZR1tofwNwLFLjeNGLWa')
expect(id).to.have.property('type', 'Ed25519')
Expand Down

0 comments on commit f1c1167

Please sign in to comment.