Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Created December 16, 2011 03:01
Show Gist options
  • Save jeffreyiacono/1484229 to your computer and use it in GitHub Desktop.
Save jeffreyiacono/1484229 to your computer and use it in GitHub Desktop.
little javascript helper
// 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