Skip to content

Commit a4c33d4

Browse files
committed
feat(streams): started the streams example implementation
1 parent f7f8b0d commit a4c33d4

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/12-streams.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'use strict';
2+
3+
var numbers = [3, 1, 7];
4+
var constant = 2;
5+
6+
function mul(a, b) {
7+
return a * b;
8+
}
9+
function print(n) {
10+
console.log(n);
11+
}
12+
var byConstant = mul.bind(null, constant);
13+
14+
// stream of numbers from an Array
15+
var util = require('util');
16+
var Readable = require('stream').Readable;
17+
util.inherits(NumberStream, Readable);
18+
19+
function NumberStream(numbers) {
20+
Readable.call(this, {
21+
objectMode: true
22+
});
23+
this.numbers = numbers;
24+
this.index = 0;
25+
}
26+
27+
NumberStream.prototype._read = function _read() {
28+
// utility functions for clarity
29+
function outputNextNumber() {
30+
this.push(this.numbers[this.index++]);
31+
}
32+
33+
function isFinished() {
34+
return this.index >= this.numbers.length;
35+
}
36+
37+
outputNextNumber.call(this);
38+
if (isFinished.call(this)) {
39+
this.push(null);
40+
}
41+
};
42+
43+
var numbers_ = new NumberStream(numbers);
44+
45+
// to just print the numbers
46+
/*
47+
numbers_.on('data', print);
48+
numbers_.on('end', function () {
49+
console.log('numbers stream finished');
50+
});*/
51+
52+

0 commit comments

Comments
 (0)