Skip to content

Instantly share code, notes, and snippets.

@Goblinlordx
Created October 6, 2020 03:10
Show Gist options
  • Save Goblinlordx/b11ff7995ff3a724549a93a4ca7044c1 to your computer and use it in GitHub Desktop.
Save Goblinlordx/b11ff7995ff3a724549a93a4ca7044c1 to your computer and use it in GitHub Desktop.
Restructuring of event task system
// Standalone queue
const AsyncQueue = () => {
let p = Promise.resolve();
return (...args) => {
p = p.then(createTask(...args));
return p;
};
}
// With existing queue data (q is existing data)
const AsyncQueueWithExisting = (q, createTask) => {
let p = q.reduce((a, params) => a.then(createTask(...params)), Promise.resolve());
return (...args) => {
p = p.then(createTask(...args));
return p;
};
}
// Example usage (existing data on window.q and existing q function on window.bzevents):
window.q = [];
window.bzevents = (...args) => q.push(args);
bzevents(1000, "test1")
bzevents(1000, "test2")
// Async code loaded and initializes with existing data
const exampleCreateTask = (n, str) => () => new Promise(resolve => setTimeout(resolve, n)).then(() => console.log("Received:", str));
window.bzevents = AsyncQueueWithExisting(window.q, exampleCreateTask);
// Events added later
bzevents(1000, "test3")
bzevents(1000, "test4")
bzevents(1000, "test5")
const CreateSendTask = () => {
const params = {
};
const userEvent = (input, type) => {
if (!params.dsID) {
console.error("Data source ID has not been set.");
return;
}
};
const types = {
init: v => {
params.dsID = v;
sendWithoutDelay()
},
setUserIDs: obj => Object.assign(params, obj),
track: v => v && userEvent({type: "event", ...v}),
setUserProperties: v => v && userEvent({type: "property", ...v}),
};
return (type, param) => {
const fn = types[type];
if (!fn) return;
return fn(param);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment