diff --git a/06-queues/projects/final/lib/ring_buffer.dart b/06-queues/projects/final/lib/ring_buffer.dart index 1218f9c..a2d4a23 100644 --- a/06-queues/projects/final/lib/ring_buffer.dart +++ b/06-queues/projects/final/lib/ring_buffer.dart @@ -20,9 +20,7 @@ class RingBuffer { _size++; } - int _advance(int index) { - return (index == _list.length - 1) ? 0 : index + 1; - } + int _advance(int index) => (index + 1) % _list.length; E? read() { if (isEmpty) return null; @@ -38,13 +36,12 @@ class RingBuffer { String toString() { final text = StringBuffer(); text.write('['); - int index = _readIndex; - while (index != _writeIndex) { + for (int i = 0; i < _size; i++) { + final index = (_readIndex + i) % _list.length; if (index != _readIndex) { text.write(', '); } - text.write(_list[index % _list.length]); - index++; + text.write(_list[index]); } text.write(']'); return text.toString(); diff --git a/06-queues/projects/final/test/ring_buffer_test.dart b/06-queues/projects/final/test/ring_buffer_test.dart index 35e477d..30d7452 100644 --- a/06-queues/projects/final/test/ring_buffer_test.dart +++ b/06-queues/projects/final/test/ring_buffer_test.dart @@ -83,13 +83,62 @@ void main() { expect(buffer.read(), isNull); }); + // https://github.com/kodecocodes/dsad-materials/pull/8 test('toString contains no infinite loop', () { - final buffer = RingBuffer(5); + final buffer = RingBuffer(3); buffer.write(1); buffer.write(2); buffer.write(3); buffer.read(); expect(buffer.toString(), '[2, 3]'); + + final rb = RingBuffer(3); + rb.write('Ray'); + rb.write('Brian'); + rb.write('Noah'); + expect(rb.read(), 'Ray'); + expect(rb.toString(), '[Brian, Noah]'); + }); + +// https://github.com/kodecocodes/dsad-materials/pull/8 + test('toString not empty when read and write index equal', () { + final rb = RingBuffer(3); + rb.write('Ray'); + rb.write('Brian'); + rb.write('Noah'); + expect(rb.toString(), '[Ray, Brian, Noah]'); + }); + + test('toString variations', () { + var buffer = RingBuffer(3); + expect(buffer.toString(), '[]'); + + buffer.write(1); + expect(buffer.toString(), '[1]'); + + buffer.write(2); + expect(buffer.toString(), '[1, 2]'); + + buffer.write(3); + expect(buffer.toString(), '[1, 2, 3]'); + + buffer.read(); + expect(buffer.toString(), '[2, 3]'); + + buffer.write(4); + expect(buffer.toString(), '[2, 3, 4]'); + + buffer.read(); + expect(buffer.toString(), '[3, 4]'); + + buffer.read(); + expect(buffer.toString(), '[4]'); + + buffer.read(); + expect(buffer.toString(), '[]'); + + buffer.read(); + expect(buffer.toString(), '[]'); }); }); }