Created
December 16, 2011 03:01
-
-
Save jeffreyiacono/1484229 to your computer and use it in GitHub Desktop.
little javascript helper
This file contains hidden or 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
// requires Underscore.js | |
var helpers = { | |
// Takes object and converts key / values to a sentence | |
// | |
// Sample usage: | |
// | |
// obj = {"this" : "is good", "that" : "is bad", "those" : "are great"} | |
// | |
// helpers.to_sentence(obj) | |
// # "this is good, that is bad, and those are great" | |
// | |
to_sentence: function(obj) { | |
var keys = _.keys(obj), | |
i = 0; | |
return _.reduce(keys, function(memo, k) { | |
memo += k + ' ' + obj[k]; | |
if (keys.length == i + 1) ; // do nothing | |
else if (keys.length == i + 2) memo += ', and ' | |
else if (keys.length > i) memo += ', ' | |
i += 1; | |
return memo; | |
}, ''); | |
} | |
}; | |
// alias it to _h for easy access! or don't. whatever | |
var _h = helpers; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment