* Pre-fetch a certain number of values from the underlying iterable before yielding the first * value. Each time a value is yielded (consumed from the buffer), another value is read from the * underlying iterable and added to the buffer. * * This is useful for maintaining a constant numb
(capacity: number)
| 104 | * @returns {Stream} A new Stream that gets its values from this Stream. |
| 105 | */ |
| 106 | buffer(capacity: number) { |
| 107 | return new Stream((function* () { |
| 108 | const b = []; |
| 109 | try { |
| 110 | // @ts-ignore |
| 111 | for (const v of this) { |
| 112 | Promise.resolve(v).catch(() => {}); // Suppress unhandled rejection errors. |
| 113 | // Note: V8 has good Array push+shift optimization. |
| 114 | while (b.length >= capacity) yield b.shift(); |
| 115 | b.push(v); |
| 116 | } |
| 117 | while (b.length) yield b.shift(); |
| 118 | } finally { |
| 119 | for (const v of b) Promise.resolve(v).then(() => {}); // Un-suppress unhandled rejections. |
| 120 | } |
| 121 | }).call(this)); |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Like Array.map(). |
no test coverage detected