Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active June 14, 2018 20:43
Show Gist options
  • Save softwarespot/6e84630fda3b90a0478630eaa83d4228 to your computer and use it in GitHub Desktop.
Save softwarespot/6e84630fda3b90a0478630eaa83d4228 to your computer and use it in GitHub Desktop.
Simple queue implementation
// For Quokka, as localStorage is not available in Node.js
const localStorage = {
getItem(name) {
return localStorage[name];
},
setItem(name, value) {
localStorage[name] = value;
},
};
const queue = {
items: [],
fn: null,
namespace: '__queue__',
// Public
start(fn) {
if (this.fn) {
throw new Error('Queue has already started');
}
if (typeof fn !== 'function') {
throw new Error(`Invalid type for "fn" argument, got "${typeof fn}"`);
}
this.fn = fn;
this.next();
},
push(item) {
const isFirst = this.items.push(item) === 1;
this.save();
if (isFirst && this.fn) {
this.next();
}
},
import() {
try {
this.items = [
...JSON.parse(localStorage.getItem(this.namespace)),
...this.items,
];
} catch (ex) {
// Ignore
}
},
reset() {
this.items.length = 0;
},
save() {
localStorage.setItem(this.namespace, JSON.stringify(this.items));
},
// Internal
next(dequeue = false) {
if (dequeue) {
this.items.shift();
this.save();
}
if (this.items.length > 0) {
const item = this.items[0];
this.fn(item, this.next.bind(this, true), this.cancel.bind(this));
}
},
cancel() {
console.error(`An error occurred with the queue item "${this.items[0]}". The queue has stopped`);
this.reset();
},
};
queue.import();
queue.push(1);
queue.push(2);
queue.push(3);
queue.start(request);
queue.push(4);
queue.push(5);
function request(num, next, cancel) {
const delay = num * 200;
setTimeout(() => {
console.log('Num:', num, 'Delay:', delay);
if (Math.random() < 0.5) {
next();
} else {
cancel();
console.log(localStorage.__queue__);
}
}, delay);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment