'use strict'

var semver = require('semver')
var DepDb = require('dependency-db')

module.exports = function (db, name, range) {
  range = String(range || '*')

  var depDb = new DepDb(db)

  if (!name) throw new Error('missing required name')

  console.log('Looking up %s %s dependants...', name, range)

  var pkgCount = 0
  var uniqueCount = 0
  var prevPkg
  var results = depDb.query(name, range)

  results.on('error', function (err) {
    throw err
  })

  results.on('data', function (pkg) {
    pkgCount++

    if (prevPkg && prevPkg.name !== pkg.name) {
      flush()
    } else if (prevPkg && semver.lt(pkg.version, prevPkg.version)) {
      return
    }

    prevPkg = pkg
  })

  results.on('end', function () {
    flush()
    console.log('Found %d dependant package releases', pkgCount)
    console.log('Filtered down to %d unique packages:', uniqueCount)
  })

  function flush () {
    uniqueCount++
    console.log('- %s@%s (latest dependency: %s)', prevPkg.name, prevPkg.version, prevPkg.dependencies[name])
  }
}

@@ -347,23 +347,63 @@
 0%0A  var 
-prevPkg
+lastName%0A  var lastVersion%0A  var lastDependency
 %0A  var r
@@ -562,28 +562,25 @@
 if (
-prevPkg && prevPkg.n
+lastName && lastN
 ame 
@@ -624,23 +624,27 @@
 lse if (
-prevPkg
+lastVersion
  && semv
@@ -662,25 +662,21 @@
 ersion, 
-prevPkg.v
+lastV
 ersion))
@@ -706,21 +706,101 @@
     
-prevPkg = pkg
+lastName = pkg.name%0A    lastVersion = pkg.version%0A    lastDependency = pkg.dependencies%5Bname%5D
 %0A  %7D
@@ -1083,65 +1083,45 @@
 )', 
-prevPkg.name, prevPkg.version, prevPkg.dependencies%5Bname%5D
+lastName, lastVersion, lastDependency
 )%0A  

Optimize memory when querying