Sugar is an amazing JavaScript library that extends a lot of the native JavaScript types and brings in similar functionality to JavaScript that ActiveSupport brings to Ruby. It is usually overlooked when compared to the similar JavaScript library underscore.js although it provides the same functionality plus additional features.
I find myself using Sugar on a daily basis these days working with AngularJS and Node.js. I prefer it over underscore.js for a few reasons.
- Sugar extends native types so I don't have to use a wrapper method on arrays, numbers and strings (although you need to wrap objects).
- Sugar has a much wider variety of methods including methods for strings, numbers and dates.
- Sugar's syntax is more natural to me coming from Ruby on Rails and ActiveSupport.
- It's modular so you can pick and choose the functionality that you need.
I still think underscore.js is an amazing library and if you are looking for a speedier, lighter alternative it does the job just fine. As a bonus underscore.js also includes templating built in something that Sugar is sorely lacking.
Here are a few examples of methods that I find myself using frequently.
Relative Time
I really love time_ago_in_words
when working with Rails. Sugar has the same functionality although a little bit different.
Date.create('2013-02-10').relative(); // 5 days ago
As a bonus, a filter that I use in AngularJS frequently:
app.filter('timeAgo', function () {
return function (date) {
return Date.create(date).relative();
};
})
Then in your template you can use the following:
<p class="date">{{updated|timeAgo}}</p>
Creating Slugs
I build a lot of CMS type systems, most of the time I will use slugs for friendly urls. Before I would generate them based on the name or title server side but now I usually add a field below the title that generates the slug based on the title and still allows the author to modify it if they want.
$('.slug').val($('.title').parameterize());
The parameterize
method above strips out any non [a-zA-z0-9]
characters and replaces them with dashes.
Finding elements in Arrays
Sugar makes it really easy to find elements in arrays. It extends the array prototype with the find
method and allows you to search using a string, number, array, object, or alternately test against a function or regex.
var games = [
{id: 1, title: 'Super Mario World'},
{id: 2, title: 'Halo 4'},
{id: 3, title: 'Grand Theft Auto'},
{id: 4, title: 'Sonic the Hedgehog'},
{id: 5, title: 'God of War'}
];
var mario = games.find(function (g) {
return g.title == 'Super Mario World';
});
var sonic = games.find(function (g) {
return g.id == 4;
});
These are just a few examples of Sugar's functionality. To learn more check out the examples on their site and read the docs and API.