Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add iterator.seek #237

Merged
merged 1 commit into from
Jun 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ A range option that is either an empty buffer, an empty string or `null` will be
Provided with the current instance of `AbstractLevelDOWN` by default.

### `AbstractIterator#_next(callback)`
### `AbstractIterator#_seek(target)`
### `AbstractIterator#_end(callback)`

### `AbstractChainedBatch`
Expand Down
16 changes: 16 additions & 0 deletions abstract-iterator.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ AbstractIterator.prototype._next = function (callback) {
process.nextTick(callback)
}

AbstractIterator.prototype.seek = function (target) {
if (this._ended) {
throw new Error('cannot call seek() after end()')
}
if (this._nexting) {
throw new Error('cannot call seek() before next() has completed')
}

target = this.db._serializeKey(target)
this._seek(target)
}

AbstractIterator.prototype._seek = function (callback) {
process.nextTick(callback)
}

AbstractIterator.prototype.end = function (callback) {
if (typeof callback !== 'function') {
throw new Error('end() requires a callback argument')
Expand Down
25 changes: 25 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,31 @@ test('test serialization extensibility (batch array is not mutated)', function (
t.equal(op.value, 'nope', 'did not mutate input value')
})

test('test serialization extensibility (iterator seek)', function (t) {
t.plan(3)

var spy = sinon.spy()
var TestIterator = implement(AbstractIterator, { _seek: spy })

var Test = implement(AbstractLevelDOWN, {
_iterator: function () {
return new TestIterator(this)
},
_serializeKey: function (key) {
t.equal(key, 'target')
return 'serialized'
}
})

var test = new Test('foobar')
var it = test.iterator()

it.seek('target')

t.equal(spy.callCount, 1, 'got _seek() call')
t.equal(spy.getCall(0).args[0], 'serialized', 'got expected target argument')
})

test('.status', function (t) {
t.test('empty prototype', function (t) {
var Test = implement(AbstractLevelDOWN)
Expand Down