Skip to content

Instantly share code, notes, and snippets.

@amacdougall
Created June 12, 2013 20:27
Show Gist options
  • Save amacdougall/5768817 to your computer and use it in GitHub Desktop.
Save amacdougall/5768817 to your computer and use it in GitHub Desktop.
underscore.js examples.
// traditional for loop explains HOW to do everything; can you spot the
// interesting logic?
var textAssets = [];
for (var i = 0; i < this.assets.length; i++) {
if (this.assets[i].type == "text") { // <- the ONLY interesting logic is right here
textAssets.push(this.assets[i]);
}
}
// we can skip over the looping code with underscore.js
var textAssets = _(this.assets).select(function(asset) {
return asset.type == "text";
});
// to simplify further, use a higher-order function
function hasType(type) {
return function(asset) {
return asset.type == type;
};
}
// now, you're not saying HOW you do things; just WHAT you want done
var textAssets = _(this.assets).select(hasType("text"));
// this process culminates in chains like this:
var totalColors = _.chain(allSides)
.reject(PP.Bridge.sides.match("envelope/front"))
.map(PP.Bridge.sides.spotColors.getColorsUsedOn)
.flatten()
.uniqBy("name")
.value()
.length;
/* Helper methods: underscore.js makes common operations more straightforward. */
if (target.toString() == '[object String]') {
// VanillaJS string detection
} else if (_(target).isString()) {
// underscore.js string detection
}
if (target === Object(target)) {
// VanillaJS object detection
} else if (_(target).isObject()) {
// underscore.js object detection
}
var isEmpty = true;
for (var key in object) {
isEmpty = false;
}
if (isEmpty) {
// VanillaJS empty object detection
} else if (_(object).isEmpty()) {
// underscore.js empty object detection
}
// setTimeout vs. delay may be a matter of taste...
setTimeout(function() {console.log("delayed with VanillaJS!");}, 5000);
_(function() {console.log("delayed with underscore.js!");}).delay(5000);
// but underscore.js provides more options:
var clickHandler = function(event) {
console.log("handling click!");
};
// repeated clicks cause repeated handler invocations
$("foo").on("click", _(clickHandler).delay(1000));
// repeated clicks cause a single invocation, 1000ms after the last click
$("foo").on("click", _(clickHandler).debounce(1000)); // good for user input
// only one click will be handled every 1000 ms, regardless of input
$("foo").on("click", _(clickHandler).throttle(1000)); // good for stream sampling
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment