Last active
October 2, 2023 18:53
-
-
Save SC-One/fb1560ff9c2994d8076a02b1f1672e85 to your computer and use it in GitHub Desktop.
implementation of CircularBuffer in qml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import QtQuick 2.0 | |
QtObject { | |
property int maximumSize: 10 | |
property var buffer: [] | |
property int head: 0 | |
property int size: 0 | |
function initialize() { | |
buffer = []; | |
for (var i = 0; i < maximumSize; i++) { | |
buffer.push(undefined); | |
} | |
} | |
function append(value) { | |
buffer[head] = value; | |
head = (head + 1) % maximumSize; | |
if (size < maximumSize) { | |
size++; | |
} | |
} | |
function getValue(index) { | |
if (index < 0 || index >= maximumSize) { | |
throw new Error("Index out of bounds"); | |
} | |
var realIndex = (head - size + index + maximumSize) % maximumSize; | |
return buffer[realIndex]; | |
} | |
function getSize() { | |
return size; | |
} | |
function clear() { | |
head = 0; | |
size = 0; | |
} | |
function pop() { | |
if (size > 0) { | |
var realIndex = (head - size + maximumSize) % maximumSize; | |
size--; | |
return buffer[realIndex]; | |
} else { | |
throw new Error("Buffer is empty, cannot pop."); | |
} | |
} | |
function push(value) { | |
if (size < maximumSize) { | |
size++; | |
} | |
buffer[head] = value; | |
head = (head + 1) % maximumSize; | |
} | |
function last() { | |
if (size > 0) { | |
var realIndex = (head - 1 + maximumSize) % maximumSize; | |
return buffer[realIndex]; | |
} else { | |
throw new Error("Buffer is empty."); | |
} | |
} | |
function first() { | |
if (size > 0) { | |
var realIndex = (head - size + maximumSize) % maximumSize; | |
return buffer[realIndex]; | |
} else { | |
throw new Error("Buffer is empty."); | |
} | |
} | |
function reset(newSize) { | |
maximumSize = newSize; | |
initialize(); | |
} | |
Component.onCompleted: { | |
initialize(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment