Last active
February 6, 2023 08:01
-
-
Save marco-prontera/96b68d72150b98a3efa51211e9bff723 to your computer and use it in GitHub Desktop.
JavaScript - Instant command queue pattern
This file contains 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
var icqLibrary = icqLibrary || {}; | |
icqLibrary.queue = icqLibrary.queue || []; | |
icqLibrary.queue.push(() => { | |
console.log('Queue 1'); | |
}); | |
icqLibrary.queue.push(() => { | |
console.log('Queue 2'); | |
}); | |
var icqLibrary = (function beautifulLibrary() { | |
var icqLibraryApi = buildLibrary(); | |
return icqLibraryApi; | |
function buildLibrary() { | |
if (icqLibrary == null) { | |
icqLibrary = {}; | |
switchQueueToInstantCommandExecution(); | |
return icqLibrary; | |
} | |
if (typeof icqLibrary == 'object' && Array.isArray(icqLibrary.queue)) { | |
icqLibrary.queue.forEach((callback) => callback()); | |
switchQueueToInstantCommandExecution(); | |
return icqLibrary; | |
} | |
throw new Error('It seems that you are using my wonderful library in a wrong way.'); | |
} | |
function switchQueueToInstantCommandExecution() { | |
icqLibrary.queue = {}; | |
icqLibrary.queue.push = function (callback) { | |
callback(); | |
}; | |
Object.freeze(icqLibrary); | |
} | |
})(); | |
icqLibrary.queue.push(() => { | |
console.log('Instant queue'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment