A utility stream for buffering results from streams that return arrays of zero or more items
You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
Sven Slootweg e98b3fa086 0.1.3 3 years ago
.gitignore Initial commit 4 years ago
README.md Update to new name 3 years ago
example.js Update to new name 3 years ago
index.js Add debugging, force sequential operation 3 years ago
package.json 0.1.3 3 years ago
yarn.lock Add debugging, force sequential operation 3 years ago

README.md

@promistream/buffer

Normally, a Promistream can only return exactly one value. A buffer stream changes this, and allows a stream to return zero-or-more values instead.

You'll probably only need this module if you're implementing a custom (transform) stream of some sort.

How it works: simply place a buffer stream after the stream whose results you want to buffer, in the pipeline. It will accept arrays of values from the previous stream, store them internally, and dispense the values in those arrays one at a time, whenever the next stream in the pipeline asks for a value.

If the previous stream returns an empty array, the buffer stream will keep requesting new values from the previous stream until it gets either a non-empty array or an EndOfStream. This is what allows streams to return zero values.

Example

In the following example, the duplicateEven stream always returns exactly one value at a time, even though the internal buffer stream receives arrays with two or zero values from the map stream before it.

This example also demonstrates how you can create custom streams by piping together existing stream modules.

"use strict";

const Promise = require("bluebird");
const pipe = require("@promistream/pipe");
const rangeNumbers = require("@promistream/range-numbers");
const map = require("@promistream/map");
const buffer = require("@promistream/buffer");
const collect = require("@promistream/collect");

function duplicateEven() {
	return pipe([
		map((value) => {
			if (value % 2 === 0) {
				return [value, value];
			} else {
				return [];
			}
		}),
		buffer()
	]);
}

return Promise.try(() => {
	return pipe([
		rangeNumbers(0, 20),
		duplicateEven(),
		collect()
	]).read();
}).then((result) => {
	console.log(result);
	// [ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14, 16, 16, 18, 18 ]
});

API

buffer()

Returns a new buffer stream. Takes no arguments.

Stream behaviour:

  • Reads from source: Zero or more times, depending on the internal buffer.
  • Consumes: An array of zero or more values. This stream will only accept arrays; any other values will result in an error.
  • Produces: Exactly one value, error, EndOfStream marker, or Aborted marker.
  • Throws: When a non-array value is consumed from the previous stream. Upstream errors are rethrown without changes.
  • Aborts: Never.