@trap_stevo/filetide
Version:
Revolutionizing real-time file transfer with seamless, instant communication across any device. Deliver files instantly, regardless of platform, and experience unparalleled speed and control in managing transfers. Elevate your file-sharing capabilities wi
72 lines (68 loc) • 2.58 kB
JavaScript
class HUDTargetQueue {
constructor() {
this.queues = new Map();
}
/**
* Adds a function to the queue for a specific ID and target value.
* @param {string} id - A unique identifier for the value being watched.
* @param {function} fn - The function to execute when the target value is reached.
*/
enqueue(id, fn) {
if (!this.queues.has(id)) {
this.queues.set(id, []);
}
this.queues.get(id).push(fn);
}
/**
* Waits for a value to change to the target value and executes only the functions
* in the queue associated with the specific ID.
* @param {string} id - A unique identifier for the value being watched.
* @param {function} getValue - A function that returns the current value.
* @param {any|array} targetValues - The value(s) to wait for.
* @param {number} interval - The interval (in milliseconds) to check the value.
* @param {number} [timeout] - Optional. The maximum time (in milliseconds) to wait before rejecting.
* @returns {Promise} - Resolves when the value matches the target value, executes queued functions.
*/
waitForData(id, getValue, targetValues, interval = 100, timeout) {
return new Promise((resolve, reject) => {
let elapsedTime = 0;
const targets = Array.isArray(targetValues) ? targetValues : [targetValues];
const checkData = async () => {
const currentValue = await getValue();
if (typeof currentValue === "object" && targets.some(target => typeof target === "object")) {
if (targets.some(target => JSON.stringify(currentValue) === JSON.stringify(target))) {
this.executeQueue(id);
resolve(currentValue);
}
} else if (targets.includes(currentValue)) {
this.executeQueue(id);
resolve(currentValue);
} else if (timeout && elapsedTime >= timeout) {
reject(new Error(`Timeout: Value did not reach target within ${timeout}ms`));
} else {
elapsedTime += interval;
setTimeout(checkData, interval);
}
};
checkData();
});
}
/**
* Executes all functions in the queue associated with the specific ID.
* @param {string} id - A unique identifier for the value being watched.
*/
executeQueue(id) {
const queue = this.queues.get(id);
if (queue) {
while (queue.length > 0) {
const fn = queue.shift();
if (typeof fn === "function") {
fn();
}
}
this.queues.delete(id);
}
}
}
module.exports = HUDTargetQueue;
;