forked from andrewosh/hypertrie-multigraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
101 lines (84 loc) · 2.31 KB
/
index.js
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
94
95
96
97
98
99
100
101
const nanoiterator = require('nanoiterator')
const dwebtrie = require('dwebtrie')
const maybe = require('call-me-maybe')
const StackIterator = require('stackable-nanoiterator')
class DWebTrieGraph {
constructor (storage, opts) {
this.trie = dwebtrie(storage, opts)
this.ready = this.trie.ready.bind(this.trie)
this._opts = opts
}
_key (opts = {}) {
var key = '/'
if (opts.label) key += opts.label
if (opts.from) key += '/' + opts.from
if (opts.to) key += '/' + opts.to
return key
}
put (from, to, label, cb) {
const key = this._key({ label, from, to })
return maybe(cb, new Promise((resolve, reject) => {
this.trie.put(key, null, err => {
if (err) return reject(err)
return resolve()
})
}))
}
del (from, to, label, cb) {
const key = this._key({ label, from, to })
return maybe(cb, new Promise((resolve, reject) => {
this.trie.del(key, err => {
if (err) return reject(err)
return resolve()
})
}))
}
batch (ops, cb) {
ops = ops.map(({ from, to, label, type }) => {
return {
key: this._key({ from, to, label }),
type,
value: null
}
})
return maybe(cb, new Promise((resolve, reject) => {
this.trie.batch(ops, err => {
if (err) return reject(err)
return resolve()
})
}))
}
iterator (opts = {}) {
const self = this
const ite = new StackIterator({
maxDepth: opts.depth
})
const visited = new Set()
ite.push(this.trie.iterator(this._key(opts), { recursive: true }))
return nanoiterator({ next })
function next (cb) {
ite.next((err, node) => {
if (err) return cb(err)
if (!node) return cb(null, null)
if (visited.has(node.key)) return next(cb)
const split = node.key.split('/')
const [, from, to] = split
const nextPrefix = self._key({
...opts,
from: to
})
ite.push(self.trie.iterator(nextPrefix))
visited.add(node.key)
return cb(null, { from, to })
})
}
}
replicate (isInitiator, opts) {
return this.trie.replicate(isInitiator, opts)
}
close (cb) {
if (!this.trie.feed) return process.nextTick(cb, null)
return this.trie.feed.close(cb)
}
}
module.exports = DWebTrieGraph