Skip to content

Instantly share code, notes, and snippets.

@piercemoore
Last active December 15, 2015 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piercemoore/5284406 to your computer and use it in GitHub Desktop.
Save piercemoore/5284406 to your computer and use it in GitHub Desktop.
Compilation of Awesome and Mega-Useful Underscore.js Mixins
/**
* All of the following Mixins are credited to their original authors, I DID NOT write ANY of these awesome things
* unless I specifically commented immediately preceding the mixin.
*/
// underscore-pickrandom.js
// (c) 2012 Simon Kågedal Reimer
// This file is freely distributable under the MIT license.
// https://gist.github.com/skagedal/1709989
// _.pickRandom - a mixin for underscore.js.
//
// Pick random elements from an array. Works similar to
// `_.first(_.shuffle(array, n))`, but is more efficient -- operates
// in time proportional to `n` rather than the length of the whole
// array.
//
// If the argument `n` is given, an array is returned.
// If no `n` is specified, only the one element is returned. This also
// happens if three or more arguments are specified -- this is so that
// _.map(array, _.pickRandom) will work as expected. This behavior is
// similar to other underscore functions, such as `_.first`.
//
// The algorithms mutates the input array while working, but restores
// everything before returning. This provides for an optimally
// efficient algorithm in all situations.
_.mixin({
pickRandom: function(array, n, guard) {
if (n == null || guard)
return array[Math.floor(Math.random() * array.length)];
n = Math.max(0, Math.min(array.length, n));
return (function pickR(array, n, length) {
var i, picked, rest, hasIndex;
if (n === 0) return [];
i = Math.floor(Math.random() * length);
hasIndex = array.hasOwnProperty(i); // This is needed for restoration of dense arrays
picked = array[i];
array[i] = array[length - 1];
rest = pickR(array, n - 1, length - 1);
// Restore array
if (hasIndex) {
array[i] = picked;
} else {
delete array[i];
}
rest.push(picked);
return rest;
}) (array, n, array.length);
}
});
/**
* http://jules.boussekeyt.org/2012/profile-javascript-app.html
*/
_.mixin({
profile: function(fn) {
return function(profileId) {
// start profiler
console.profile(profileId)
// call our real function
fn.apply(this, arguments)
// stop profiler
console.profileEnd(profileId)
}
}
})
/**
* From Underscore Mixin documentation
*/
_.mixin({
capitalize : function(string) {
return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
}
});
/**
* http://mattmueller.me/blog/underscore-extension-observer-pattern
*/
_.mixin({
on : function(obj, event, callback) {
// Define a global Observer
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
if(this.isUndefined(obj._events)) obj._events = {};
if (!(event in obj._events)) obj._events[event] = [];
obj._events[event].push(callback);
return this;
},
once : function(obj, event, callback) {
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
var removeEvent = function() { _.removeEvent(obj, event); };
callback = _.compose(removeEvent, callback);
this.on(obj, event, callback);
},
emit : function(obj, event, args){
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
if(this.isUndefined(obj._events)) return;
if (event in obj._events) {
var events = obj._events[event].concat();
for (var i = 0, ii = events.length; i < ii; i++)
events[i].apply(obj, args === undefined ? [] : args);
}
return this;
},
removeEvent : function(obj, event) {
if(this.isString(obj)) { event = obj; obj = this; }
if(this.isUndefined(obj._events)) return;
console.log("remove");
delete obj._events[event];
}
});
/**
* https://gist.github.com/kof/885027
* Inherit prototype properties
* @param {Function} ctor
* @param {Function} superCtor
*/
_.mixin({
inherits: (function(){
function noop(){}
function ecma3(ctor, superCtor) {
noop.prototype = superCtor.prototype;
ctor.prototype = new noop;
ctor.prototype.constructor = superCtor;
}
function ecma5(ctor, superCtor) {
ctor.prototype = Object.create(superCtor.prototype, {
constructor: { value: ctor, enumerable: false }
});
}
return Object.create ? ecma5 : ecma3;
}())
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment