This repository has been archived by the owner on Dec 2, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
deferred-iterator.js
85 lines (67 loc) · 2.18 KB
/
deferred-iterator.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
'use strict'
const { AbstractIterator } = require('abstract-leveldown')
const inherits = require('inherits')
const getCallback = require('./util').getCallback
const kOptions = Symbol('options')
const kIterator = Symbol('iterator')
const kOperations = Symbol('operations')
const kPromise = Symbol('promise')
function DeferredIterator (db, options) {
AbstractIterator.call(this, db)
this[kOptions] = options
this[kIterator] = null
this[kOperations] = []
}
inherits(DeferredIterator, AbstractIterator)
DeferredIterator.prototype.setDb = function (db) {
this[kIterator] = db.iterator(this[kOptions])
for (const op of this[kOperations].splice(0, this[kOperations].length)) {
this[kIterator][op.method](...op.args)
}
}
DeferredIterator.prototype.next = function (...args) {
if (this.db.status === 'open') {
return this[kIterator].next(...args)
}
const callback = getCallback(args, kPromise, function map (key, value) {
if (key === undefined && value === undefined) {
return undefined
} else {
return [key, value]
}
})
if (this.db.status === 'opening') {
this[kOperations].push({ method: 'next', args })
} else {
this._nextTick(callback, new Error('Database is not open'))
}
return callback[kPromise] || this
}
DeferredIterator.prototype.seek = function (...args) {
if (this.db.status === 'open') {
this[kIterator].seek(...args)
} else if (this.db.status === 'opening') {
this[kOperations].push({ method: 'seek', args })
} else {
throw new Error('Database is not open')
}
}
DeferredIterator.prototype.end = function (...args) {
if (this.db.status === 'open') {
return this[kIterator].end(...args)
}
const callback = getCallback(args, kPromise)
if (this.db.status === 'opening') {
this[kOperations].push({ method: 'end', args })
} else {
this._nextTick(callback, new Error('Database is not open'))
}
return callback[kPromise] || this
}
for (const method of ['next', 'seek', 'end']) {
DeferredIterator.prototype['_' + method] = function () {
/* istanbul ignore next: assertion */
throw new Error('Did not expect private method to be called: ' + method)
}
}
module.exports = DeferredIterator