Skip to content
This repository has been archived by the owner on Feb 26, 2021. It is now read-only.

Commit

Permalink
feat: add filter functionality for multiaddr (#63)
Browse files Browse the repository at this point in the history
* add filter functionality for multiaddr

* Refactor filter to use mafmt

* Fix package reference
  • Loading branch information
zcstarr authored and daviddias committed Apr 9, 2018
1 parent cf71234 commit 0dc8e03
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
},
"dependencies": {
"multiaddr": "^4.0.0",
"mafmt": "^4.0.0",
"lodash.uniqby": "^4.7.0",
"peer-id": "~0.10.7"
},
Expand Down
9 changes: 9 additions & 0 deletions src/multiaddr-set.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ class MultiaddrSet {
return this._multiaddrs.forEach(fn)
}

filterBy (maFmt) {
if (typeof maFmt !== 'object' ||
typeof maFmt.matches !== 'function' ||
typeof maFmt.partialMatch !== 'function' ||
typeof maFmt.toString !== 'function') return []

return this._multiaddrs.filter((ma) => maFmt.matches(ma))
}

has (ma) {
ma = ensureMultiaddr(ma)
return this._multiaddrs.some((m) => m.equals(ma))
Expand Down
11 changes: 11 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ chai.use(dirtyChai)
const expect = chai.expect
const Id = require('peer-id')
const Multiaddr = require('multiaddr')
const mafmt = require('mafmt')
const Info = require('../src')
const peerIdJSON = require('./peer-test.json')

Expand Down Expand Up @@ -260,6 +261,16 @@ describe('peer-info', () => {
})
})

it('multiaddrs.filterBy', () => {
const ma1 = Multiaddr('/ip4/127.0.0.1/tcp/7000')
const ma2 = Multiaddr('/ip4/127.0.0.1/udp/5001')
pi.multiaddrs.add(ma1)
pi.multiaddrs.add(ma2)
const maddrs = pi.multiaddrs.filterBy(mafmt.TCP)
expect(maddrs.length).to.eq(1)
expect(maddrs[0].equals(ma1)).to.eq(true)
})

it('multiaddrs.toArray', () => {
pi.multiaddrs.add('/ip4/127.0.0.1/tcp/5001')
pi.multiaddrs.toArray().forEach((ma) => {
Expand Down

0 comments on commit 0dc8e03

Please sign in to comment.