Skip to content

Commit

Permalink
Implement sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
avinoamr committed Jun 28, 2015
1 parent 1c413d9 commit 8ac5446
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
31 changes: 19 additions & 12 deletions fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Cursor.prototype._load = function () {
var sifter = sift( this._query );
var limit = this._limit || Infinity;
var skip = this._skip || 0;
var sort = this._sort || [];
var that = this;

var seen = {};
Expand All @@ -43,13 +44,11 @@ Cursor.prototype._load = function () {
that.emit( "error", err );
})
.on( "data", function ( obj ) {
// skip everything past the limit
if ( limit <= 0 ) return;

if ( !obj.trim() ) return; // skip empty lines
try {
obj = JSON.parse( obj.trim() );
} catch ( e ) {
return;
} catch ( err ) {
return this.emit( "error", err );
}

// skip seen objects
Expand All @@ -61,15 +60,23 @@ Cursor.prototype._load = function () {

// skip objects that don't meet the query criteria
if ( !sifter.test( obj ) ) return;

if ( skip-- <= 0 ) {
results.push( obj );
limit -= 1;
}

results.push( obj );
})
.on( "end", function() {
results.reverse().forEach( that.push.bind( that ) );
results.reverse()
results.sort( function ( d1, d2 ) {
for ( var s = 0 ; s < sort.length ; s += 1 ) {
s = sort[ s ];
if ( d1[ s.key ] == d2[ s.key ] ) continue;
return d1[ s.key ] > d2[ s.key ]
? s.direction : -s.direction;
}
return 0;
})

results.splice( 0, skip )
results.splice( limit );
results.forEach( that.push.bind( that ) );
that.push( null );
that._loading = false;
});
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "dbstream-fs",
"version": "1.0.6",
"version": "1.0.7",
"description": "File-system based database compatible with the Database Stream API",
"main": "fs.js",
"scripts": {
Expand All @@ -27,7 +27,7 @@
"mocha": "^1.21.0"
},
"dependencies": {
"dbstream": "git+https://github.com/avinoamr/dbstream",
"dbstream": "^1.0.1",
"fs-reverse": "0.0.2",
"sift": "0.0.18"
}
Expand Down

0 comments on commit 8ac5446

Please sign in to comment.