-
Notifications
You must be signed in to change notification settings - Fork 443
/
map.ts
93 lines (78 loc) · 2.06 KB
/
map.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { mapIterable } from './util.js'
import type { PeerId } from '@libp2p/interface'
/**
* We can't use PeerIds as map keys because map keys are
* compared using same-value-zero equality, so this is just
* a map that stringifies the PeerIds before storing them.
*
* PeerIds cache stringified versions of themselves so this
* should be a cheap operation.
*
* @example
*
* ```TypeScript
* import { peerMap } from '@libp2p/peer-collections'
*
* const map = peerMap<string>()
* map.set(peerId, 'value')
* ```
*/
export class PeerMap <T> {
private readonly map: Map<string, { key: PeerId, value: T }>
constructor (map?: PeerMap<T>) {
this.map = new Map()
if (map != null) {
for (const [key, value] of map.entries()) {
this.map.set(key.toString(), { key, value })
}
}
}
[Symbol.iterator] (): IterableIterator<[PeerId, T]> {
return this.entries()
}
clear (): void {
this.map.clear()
}
delete (peer: PeerId): boolean {
return this.map.delete(peer.toString())
}
entries (): IterableIterator<[PeerId, T]> {
return mapIterable<[string, { key: PeerId, value: T }], [PeerId, T]>(
this.map.entries(),
(val) => {
return [val[1].key, val[1].value]
}
)
}
forEach (fn: (value: T, key: PeerId, map: PeerMap<T>) => void): void {
this.map.forEach((value, key) => {
fn(value.value, value.key, this)
})
}
get (peer: PeerId): T | undefined {
return this.map.get(peer.toString())?.value
}
has (peer: PeerId): boolean {
return this.map.has(peer.toString())
}
set (peer: PeerId, value: T): void {
this.map.set(peer.toString(), { key: peer, value })
}
keys (): IterableIterator<PeerId> {
return mapIterable<{ key: PeerId, value: T }, PeerId>(
this.map.values(),
(val) => {
return val.key
}
)
}
values (): IterableIterator<T> {
return mapIterable(this.map.values(), (val) => val.value)
}
get size (): number {
return this.map.size
}
}
export function peerMap <T> (): PeerMap<T> {
return new PeerMap<T>()
}