Mixin Catalog

typicode edited this page Sep 18, 2014 · 94 revisions
Clone this wiki locally

This page serves to catalog shared underscore mixins, here and elsewhere.

Background: Mixin Syntax
_.mixin(object)

Allows you to extend Underscore with your own utility functions. Pass a hash of {name: function} definitions to have your functions added to the Underscore object, as well as the OOP wrapper.

_.mixin({
  capitalize : function(string) {
    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  }
});
_("fabio").capitalize();
=> "Fabio"

Underscore-contrib

… is probably the single best place to start: Underscore-contrib

Underscore convenience

  • Sigfried Gold offers underscore-unchained, which attaches underscore methods to objects at will and also to their results, so calling chain is unnecessary: var arr = _.unchain(['a','bb','ccc']); arr.pluck('length').last().range() // [0, 1, 2]

Strings

  • Esa-Matti Suuronen has a sweet git repo named underscore.string which adds many string functions to Underscore.js through mixins.
  • Jos de Jong created a mixin interpolate, which substitutes properties in a string, for example: _var msg = _interpolate('Hello, $name!', {name: 'Jos'})

Misc Mixins in the Wild

(update me!)

  • Typicode, underscore-db – Adds database-like functions (insert, get, save, load, …) for turning objects into small databases.
  • Jmeas, Underscore Medley – `containsAny`, `containsAll`, `isSet`, the last of which determines whether it’s safe to access an object’s properties.
  • Kyle Traff, _struct.js adds some of the best functional data structures to the Underscore library: _.zipper([ 1, 2, 3, 4, 5]).right(4).left().val() // 4
  • Andrea Puddu, squeeze – or JSON extract/flatten – Returns an array with only the string values of the given object (any depth).
  • David Beck, underscore-template-helpers is a mixin that allows you to define global helper functions that will always be available in your underscore templates.
  • Mike Jones, Underscore.altWhere Extends the _.where concept to return object members based on a choice of values in a key:value pair.
  • Elliot Chong, underscore.deepExtend allows you to deeply combine two or more objects that share common object keys. Useful for combining complex hashmaps, such as: _.deepExtend({ "name": { "first": "Earl" }, "job": "Mad Scientist" }, { "name": { "last": "Duncan" }}); results in { "name": { "first": "Earl", "last": "Duncan" }, "job": "Mad Scientist" }
  • Tim Wood created a mixin called Moment.js (originally “underscore.date”) that parses, validates, manipulates, and displays dates.
  • Omar Yasin published a mixin in this gist that provides a ‘printf’-like functionality
  • Xavier Spriet has this gist that has a mixin to emulate ruby’s Array#each_slice method.
  • Francesco Agati provides this gist with _.selectIf
  • Steven Black, in this gist _.filterObj: Return an object who’s members are culled to match a reference array of keys.
  • thegrandpoobah suggests this _.retry mixin.
  • Arnau Sanchez: Mixins: merge, mash, takeWhile, mapDetect, uniqWith, flatten1.
  • Paul Harper (benekastah): underscore.loop – adds scheme/clojure like recursive looping with tail-call optimization.
  • Kevin Malakoff (kmalakoff): underscore-awesomer – many “awesome” functions like ‘toJSON’/‘parseJSON’ for instance serializaion/deserializaion, ‘compare’, ‘keypath’ for accessing nested properties, ‘remove’, ‘own’/‘disown’, ‘cloneToDepth’, ‘toType’ conversions using to{X} function as a fallback if the types don’t match, etc.
  • Julian Burgess (aubergene): _.rotate – Array rotate mixin
  • Trevor Parscal (trevorparscal): more-underscore – More stuff for underscore, such as ‘extendClass’ (prototypical inheritance), ‘objectify’ (combine array values with property names) and ‘traverse’ (get a value from a multi-level collection using an array of keys and indexes).
  • tobias104 provides this _.indexBy gist – Combination of _.find and _.indexOf, that returns the index of the first item that passes the test.
  • Mark Rushakoff (mark-rushakoff): function binding helpers – provides two functions similar to _.bindAll. _.bindFiltered takes a filter function that operates on function names, and _.bindMatching takes a regex for the names of which functions to bind.
  • Adrian Rossouw (Vertice): Partial function application binders – provides a function called _.partial which allows you to bind specific arguments, leaving a closure. Also contains a _.wrapAsync, which turns non-async calls into the format node.js expects. _.partialAsync does both.
  • Simon Kågedal Reimer (skagedal): underscore-pickrandom.js — provides a function, _.pickRandom(array, [n]) that picks random elements from an array. It works similar to _.first(_.shuffle(array, n)), but is more efficient; it operates in time proportional to n rather than the length of the whole array.
  • Tony Stuck (toekneestuck): underscore.nl2br – A simple port of nl2br to Underscore for string manipulation.
  • Ross Cairns (rc1): body – provides the middle/body of an Array.
  • Brian LK (1337): seq – executes a list of functions in sequence, each provided with the return of the previous one.
  • Yann Eves (aaunel): serialize – serialize key-value pairs of an object into urlencoded format, imitates jQuery’s ‘$.param’.

Discussion

This page is a bit hard to browse and quickly find what you need. I’d suggest: 1. group mixins by functionality; 2. emphasize what functions each mixin provides with a short description for each function (more like the underscore main page); 3. put less emphasis on the author. /skagedal (sorry if this isn’t the proper way of discussing wiki pages)