factory.js (2411B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var copy = require( '@stdlib/utils/copy' ); 24 var IteratorStream = require( './main.js' ); 25 26 27 // MAIN // 28 29 /** 30 * Returns a function for creating readable streams from iterators. 31 * 32 * @param {Options} [options] - stream options 33 * @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode 34 * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` 35 * @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before pausing iteration 36 * @param {string} [options.sep='\n'] - separator used to join streamed data 37 * @param {Function} [options.serialize] - custom serialization function 38 * @returns {Function} stream factory 39 * 40 * @example 41 * var randu = require( '@stdlib/random/iter/randu' ); 42 * 43 * var opts = { 44 * 'sep': ',', 45 * 'objectMode': false, 46 * 'encoding': 'utf8', 47 * 'highWaterMark': 64 48 * }; 49 * 50 * var createStream = factory( opts ); 51 * 52 * // Create 10 identically configured streams... 53 * var streams = []; 54 * var i; 55 * for ( i = 0; i < 10; i++ ) { 56 * streams.push( createStream( randu() ) ); 57 * } 58 */ 59 function factory( options ) { 60 var opts; 61 if ( arguments.length ) { 62 opts = copy( options, 1 ); 63 } else { 64 opts = {}; 65 } 66 return createStream; 67 68 /** 69 * Returns a readable stream from an iterator. 70 * 71 * @private 72 * @param {Iterator} iterator - source iterator 73 * @throws {TypeError} must provide an iterator 74 * @throws {TypeError} options argument must be an object 75 * @throws {TypeError} must provide valid options 76 * @returns {IteratorStream} Stream instance 77 */ 78 function createStream( iterator ) { 79 return new IteratorStream( iterator, opts ); 80 } 81 } 82 83 84 // EXPORTS // 85 86 module.exports = factory;