Skip to content

Commit a52026f

Browse files
committed
fix streams
1 parent 263c9ee commit a52026f

File tree

2 files changed

+37
-8
lines changed

2 files changed

+37
-8
lines changed

lib/index.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,16 @@ module.exports = class RingBuffer{
88
constructor ( size ) {
99
this.size = size
1010
this.sizei = size - 1
11-
this.buffer = new Array(size)
11+
this.buffer = new Array(size)
1212
this.pointer = 0
1313
}
1414

1515
add (item) {
1616
this.buffer[this.pointer] = item
1717
this.pointer = ( this.size + this.pointer + 1 ) % this.size
18+
return true
1819
}
19-
20+
2021
get (i) {
2122
return this.buffer[i]
2223
}
@@ -25,23 +26,32 @@ module.exports = class RingBuffer{
2526
let index = ( this.size + this.pointer - 1 ) % this.size
2627
return this.buffer[index]
2728
}
28-
29+
2930
toArray(){
3031
let res = this.buffer.slice(this.pointer, this.size)
3132
if ( this.pointer > 0 )
3233
res = res.concat(this.buffer.slice(0, this.pointer))
3334
return res
34-
}
35-
35+
}
36+
3637
clear(){
3738
this.buffer = new Array(this.size)
3839
this.pointer = 0
3940
return true
4041
}
41-
42+
4243
writeStream(){
4344
if ( this.stream ) return this.stream
44-
return this.stream = new require('stream').Writable({ write: (chunk)=> this.add(chunk) })
45+
return this.stream = new require('stream').Writable({
46+
write: (chunk, enc, next)=> {
47+
try {
48+
this.add(chunk)
49+
} catch (err) {
50+
next(err)
51+
}
52+
next()
53+
}
54+
})
4555
}
4656

4757
}

test/unit_package_spec.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
const expect = require('chai').expect
12
const RingBuffer = require('../')
23

4+
35
describe('Unit::deployable-ringbuffer', function(){
46

57
describe('Something does something', function(){
6-
8+
79
it('should create a RingBuffer', function(){
810
expect( new RingBuffer(5) ).to.be.ok
911
})
@@ -31,6 +33,14 @@ describe('Unit::deployable-ringbuffer', function(){
3133
expect( rb.last() ).to.equal('two')
3234
})
3335

36+
it('should get the last added when added', function(){
37+
let rb = new RingBuffer(100)
38+
rb.add('first')
39+
expect( rb.last() ).to.equal('first')
40+
rb.add('second')
41+
expect( rb.last() ).to.equal('second')
42+
})
43+
3444
it('should get undefined when there is no last', function(){
3545
let rb = new RingBuffer(3)
3646
expect( rb.last() ).to.equal( undefined )
@@ -77,6 +87,15 @@ describe('Unit::deployable-ringbuffer', function(){
7787
expect( rb.last().toString() ).to.equal( 'test' )
7888
})
7989

90+
it('should return a write stream', function(){
91+
let rb = new RingBuffer(2)
92+
let ws = rb.writeStream()
93+
ws.write('test')
94+
ws.write('testa')
95+
ws.write('testb')
96+
expect( rb.last().toString() ).to.equal( 'testb' )
97+
})
98+
8099
})
81100

82101
})

0 commit comments

Comments
 (0)