Skip to content

Instantly share code, notes, and snippets.

@elkorn
Last active September 18, 2016 08:21
Show Gist options
  • Save elkorn/6073935 to your computer and use it in GitHub Desktop.
Save elkorn/6073935 to your computer and use it in GitHub Desktop.
Various useful utility functions
/**
* Finds the first occurence of an element specified by the given function in a collection.
*
* @method findFirst
* @param {Array} collection The collection to search.
* @param {Function} fn The selector function used to find an element.
* @return {*} The first occurence of the element.
*/
function findFirst(collection) {
return function(fn) {
var result;
collection.some(function(element, index){
if(fn(element,index)) {
result = element;
return true;
}
});
return result;
}
}
/**
* Performs an operation for a given range of numbers.
*/
function inRange(start, end, modifier) {
return Array.apply(null, {
length: end - start + 1
}).map(Number.call, function(e) {
return modifier(e + start);
});
}
// Only add setZeroTimeout to the window object, and hide everything
// else in a closure.
(function() {
var timeouts = [];
var messageName = "zero-timeout-message";
// Like setTimeout, but only takes a function argument. There's
// no time argument (always zero) and no arguments (you have to
// use a closure).
function setZeroTimeout(fn) {
timeouts.push(fn);
window.postMessage(messageName, "*");
}
function handleMessage(event) {
if (event.source == window && event.data == messageName) {
event.stopPropagation();
if (timeouts.length > 0) {
var fn = timeouts.shift();
fn();
}
}
}
window.addEventListener("message", handleMessage, true);
// Add the one thing we want added to the window object.
window.setZeroTimeout = setZeroTimeout;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment