@@ -8,18 +8,46 @@ function Iterator (db, options) {
88 AbstractIterator . call ( this , db )
99 this . _order = ! ! options . reverse ? 'DESC' : 'ASC'
1010 this . _start = options . start
11+ this . _limit = options . limit
12+ if ( this . _limit ) this . _count = 0
1113 this . _end = options . end
1214 this . _done = false
1315}
1416
1517util . inherits ( Iterator , AbstractIterator )
1618
1719Iterator . prototype . createIterator = function ( ) {
18- if ( typeof this . _start !== 'undefined' || typeof this . _end !== 'undefined' ) {
20+ var lower , upper
21+ var onlyStart = typeof this . _start !== 'undefined' && typeof this . _end === 'undefined'
22+ var onlyEnd = typeof this . _start === 'undefined' && typeof this . _end !== 'undefined'
23+ var startAndEnd = typeof this . _start !== 'undefined' && typeof this . _end !== 'undefined'
24+ if ( onlyStart ) {
25+ var index = this . _start
26+ if ( this . _order === 'ASC' ) {
27+ lower = index
28+ } else {
29+ upper = index
30+ }
31+ } else if ( onlyEnd ) {
32+ var index = this . _end
33+ if ( this . _order === 'DESC' ) {
34+ lower = index
35+ } else {
36+ upper = index
37+ }
38+ } else if ( startAndEnd ) {
39+ lower = this . _start
40+ upper = this . _end
41+ if ( this . _start > this . _end ) {
42+ lower = this . _end
43+ upper = this . _start
44+ }
45+ }
46+ if ( lower || upper ) {
1947 this . _keyRange = this . options . keyRange || this . db . makeKeyRange ( {
20- lower : this . _start ,
21- upper : this . _end
22- // todo excludeUpper/excludeLower
48+ lower : lower ,
49+ upper : upper
50+ // todo expose excludeUpper/excludeLower
2351 } )
2452 }
2553 this . iterator = this . db . iterate ( this . onItem . bind ( this ) , {
@@ -30,11 +58,21 @@ Iterator.prototype.createIterator = function() {
3058 } )
3159}
3260
61+ // TODO the limit implementation here just ignores all reads after limit has been reached
62+ // it should cancel the iterator instead but I don't know how
3363Iterator . prototype . onItem = function ( cursor , cursorTransaction ) {
34- if ( ! cursor && this . callback ) return this . callback ( )
35- if ( this . callback ) this . callback ( false , cursor . key , cursor . value )
36- this . callback = false
37- cursor . continue ( )
64+ if ( ! cursor && this . callback ) {
65+ this . callback ( )
66+ this . callback = false
67+ return
68+ }
69+ if ( this . _limit ) {
70+ if ( this . _limit > this . _count ) this . callback ( false , cursor . key , cursor . value )
71+ } else {
72+ this . callback ( false , cursor . key , cursor . value )
73+ }
74+ if ( this . _limit ) this . _count ++
75+ if ( cursor ) cursor . continue ( )
3876}
3977
4078Iterator . prototype . _next = function ( callback ) {
0 commit comments