sorted-intersect-stream
Get the intersection of two sorted streams.
npm install sorted-intersect-stream
Usage
It is easy to use
const Intersect =const Readable =const sorted1 = Readableconst sorted2 = Readable// combine the two streams into a single intersected streamconst intersection = sorted1 sorted2intersectionintersection
Running the above example will print
intersected at 10
intersected at 42
intersected at 55
no more intersections
When the intersection ends the two input streams will be destroyed. Setintersection.autoDestroy = false
to disable this.
Streaming objects
If you are streaming objects sorting is based on the compare function you can pass as the 3rd argument.
const sorted1 = Readableconst sorted2 = Readableconst i = sorted1 sorted2 {return afoo < bfoo ? -1 : afoo > bfoo ? 1 : 0}i
A good use-case for this kind of module is implementing something like full-text search where you want to intersect multiple index hits.
Intersecting LevelDB streams
Since levelup streams are sorted in relation to their keys it is easy to intersect them using sorted-intersect-stream.
If we wanted to intersect two namespaces foo
and bar
we could do it like so
const db =const foo = dbconst bar = dbconst intersection = foo bar {const aKey =const bKey =return aKey < bKey ? -1 : aKey > bKey ? 1 : 0}{// remove the namespace from the keys so they are comparablereturn datakey}
License
MIT