Skip to content

Instantly share code, notes, and snippets.

@jpmckinney
Created March 23, 2011 18:03
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 jpmckinney/883598 to your computer and use it in GitHub Desktop.
Save jpmckinney/883598 to your computer and use it in GitHub Desktop.
Mixins for Underscore.js
// blog post: http://blog.slashpoundbang.com/post/4047203519/mixins-for-underscore-js
_.mixin({
// @param array obj An array of two-element arrays, where the first element is
// the key and the second element is the value.
// @returns object A JavaScript object declaring key-value pairs.
toObj: function (obj) {
return _.reduce(obj, function (memo, array) {
memo[array[0]] = array[1];
return memo;
}, {});
},
// @param object obj A JavaScript object declaring key-value pairs.
// @param function iterator The sorting function.
// @param context context A context (optional).
// @returns object obj The JavaScript object with its key-value pairs sorted
// by value according to the sorting function.
sortObj: function (obj, iterator, context) {
return _.toObj(_.pluck(_.map(obj, function(value, index, list) {
return {
value : [index, value],
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value'));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment