Skip to content
This repository has been archived by the owner on Dec 1, 2024. It is now read-only.

Commit

Permalink
add iterator.seek (#237)
Browse files Browse the repository at this point in the history
  • Loading branch information
vweevers authored Jun 17, 2018
1 parent 0b2949a commit d806bf1
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
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

0 comments on commit d806bf1

Please sign in to comment.