Created
October 7, 2015 20:55
-
-
Save softwarespot/7199f67b220dbf992c3b to your computer and use it in GitHub Desktop.
Interview example
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
// Note: Save as Company.js and run 'babel-node Company.js' to display in the command window. This is written in ES2015 | |
const Company = ((window) => { | |
// Store an array of callbacks | |
const _callbacks = []; | |
// Store whether the 'init' function has already been called | |
let _isInitialised = false; | |
function init() { | |
_isInitialised = true; | |
while (_callbacks.length > 0) { | |
// This is the same as using a queue, where the first callback enqueued is dequeued etc... | |
const callback = _callbacks.shift(); | |
// Call the callback | |
callback(); // Could use callback.call(); to change the context | |
} | |
} | |
function ready(...callbacks) { | |
// If 'init' has already been called, then just call the array of 'callbacks' | |
if (_isInitialised) { | |
for (const callback of callbacks) { | |
window.console.log('Ready after initialisation'); | |
// Call the callback | |
callback(); // Could use callback.call(); to change the context | |
} | |
return; | |
} | |
// Add the callback arguments to the array, but only if a function type | |
for (const callback of callbacks) { | |
if (Object.prototype.toString.call(callback) === '[object Function]') { | |
window.console.log('Ready before initialisation'); | |
_callbacks.push(callback); | |
} | |
} | |
} | |
// Public API | |
return { | |
init: init, | |
ready: ready | |
}; | |
})(window); | |
// Example, with private scope | |
((window, global) => { | |
function example1() { | |
window.console.log('Example function => 1'); | |
} | |
function example2() { | |
window.console.log('Example function => 2'); | |
} | |
function example3() { | |
window.console.log('Example function => 3'); | |
} | |
function example4() { | |
window.console.log('Example function => 4'); | |
} | |
// Add three callback functions to be called when 'init' is invoked | |
global.ready(example1, example2, example3); | |
// After 3 seconds, call the 'init' function | |
window.setTimeout(() => { | |
global.init(); | |
window.console.log('Init finally invoked...'); | |
// This will execute immediately due to 'init' having already been called | |
global.ready(example4); | |
}, 3000); | |
console.log('Lets wait for 3 seconds...'); | |
})(window, Company); // Pass 'Company' to the IIFE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment