Created
March 23, 2011 18:03
-
-
Save jpmckinney/883598 to your computer and use it in GitHub Desktop.
Mixins for Underscore.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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