Playing with Sugar.js

Introduction

Did you ever need the functionality to get the first 2 items in a JavaScript array? Or get the average of all the items? Or maybe sort the items in the array by its length? Or functions for determining if a string has Japanese or Greek characters? Or maybe formatting dates into their string versions? Or getting the exact date from today after 5 months?
Did you ever wish for JavaScript to have these functions built-in to it and that you could easily call it without having to create your own functions?

Now you can have all of these functions by using a library called Sugar.js. It’s sort of like Underscore.js that serves as a utility belt for JavaScript. Most of the functions that you wished JavaScript have for manipulating Strings, Arrays, Dates, and Objects is already included in Sugar.js.

In this article I’ll be giving you an introduction on Sugar.js, what sort of things you can do with it, the functions that you can use for manipulating Strings, Arrays and Objects. I’ll also show you how to write the equivalent of those Sugar.js functions in plain JavaScript function and extending the JavaScript Prototype.
So yeah, let’s get started and play with it. I’ve already linked each of the functions to a fiddle so that you can play with it. I didn’t have any luck including fiddles for the Sugar.js scripts so you might as well play on the Sugar.js site. You can actually edit the sample scripts and see the output right away.

Arrays

Getting a specified number of items from an array starting from index 0.

Sugar.js:

[4, 5, 6, 7].first(2) //output: [4, 5]

Plain JavaScript Function:

function get_first(array, num){
   var new_array = [];

   for(var x = 0; x<num; x++){
      new_array[x] = array[x];
   }
   return new_array;
}
//call: get_first([4,5,6,7], 2)
//output: [4,5]

Extending Array Prototype:

Array.prototype.get_first = function(num){
   var new_array = [];

   for(var x = 0; x<num; x++){
      new_array[x] = this[x];
   }
   return new_array;
}
//call: [1,2,3].get_first(2)
//output: [1,2]

There’s also a function for getting the average from the specified array.
Sugar.js:

   [1,2,3].average(); //output: 2

Plain JavaScript Function:

function get_average(array){
   var r_length = array.length;
   var total = 0;
   for(var x in array){
      total = total + array[x];
   }
   return parseFloat(total) / parseFloat(r_length);
}
//call: get_average([1,2,3]);
//output: 2

Extending Array Prototype:

Array.prototype.get_average = function(){
   var r_length = this.length;
   var total = 0;
   for(var x in this){
      total = total + this[x];
   }
   return parseFloat(total) / parseFloat(r_length);
}
//call: [1,2,3].get_average()
//output: 2

There’s also a function for getting the max and min values from an array.
Sugar.js:

[4, 5, 6].max() //output: 6
[10, 2, 22].min() //output: 2

Plain JavaScript Function:

function sort(array, sortby){
   if(sortby == 'ASC'){
      var val = array.sort(function(a, b){
         return b + a;
                })[0]
   }else if(sortby == 'DESC'){
      var val = array.sort(function(a, b){
         return b - a;
                })[0]
   }
   return val;
}
//call: sort([4,5,22,33,1], 'ASC')
//output: 1
//call: sort([4,5,22,33,1], 'DESC')
//output: 33

Extending Array Prototype:

Array.prototype.max = function(){
   return this.sort(function(a, b){
      return b - a;
                   })[0]
}
//call: [44,50,24,16].max()
//output: 50

 

Array.prototype.min = function(){
   return this.sort(function(a, b){
   return b + a;
                    })[0]
}
//call: [50,2,1,3,16].min()
//output: 1

Numbers

There are also functions used for manipulating numbers. Remember that numbers are delicate so don’t call functions for numbers like the way you do when calling string functions or else you’ll really get a nasty error. If you don’t know what I mean try executing a Sugar.js function normally:

6.isEven() //output: SyntaxError: Unexpected token ILLEGAL

Here’s what you can do to avoid getting errors the first method is by enclosing your number in parentheses and then call the function as you normally would:

(4).isEven() //output: true

Second method is by using bracket notation:

4['isEven']() //output: true

Plain JavaScript Function:

function even(num){
   return num % 2 === 0;
}
//call: even(4)
//output: true

 

function odd(num){
   return num % 2 !== 0;
}
//call: odd(4)
//output: false

Extending the Number Prototype:

Number.prototype.even = function(){
   return this % 2 === 0;
}
//call: 30['even']()
//output: true

 

Number.prototype.odd = function(){
return this % 2 !== 0;
}
//call: 30['odd']()
//output: false

Strings

There are also string functions used for manipulating string. Most of the functions that is included in Sugar.js are already present in plain JavaScript so I won’t use them as examples.

The first function is used for getting a part of a string from the specified index. Remember that programming languages are zero-indexed so you will need to use 0 if you want to get the 1st character, 1 if you want to get the 2nd character and so on.

Sugar.js

'super_duper_cool'.from(12) //output: cool

<strong><span style=”font-size: small;”>Plain JavaScript Function:</span></strong>

function from(str, frm){
   var last = str.length;
   return str.substr(frm, last);
}
//call: from("javascriptiscool", 12)
//output: cool

Extending the String Prototype:

String.prototype.start_from = function(frm){
   var last = this.length;
   return this.substr(frm, last);
}
//call: "youareawesome".start_from(3)
//out: areawesome

Conclusion

Sugar.js is a really nice way to extend the functions that are already built in to JavaScript. If you’re looking for a quick and dirty solution for your JavaScript problems Sugar.js is a way to go. It’s also useful if you want to save time in writing functions from scratch. But if you’re still a JavaScript beginner just like me I would recommend that you go ahead and check out the functions in Sugar.js or Underscore.js and see if you can build those functions from scratch just like what I did here. You could learn a lot in writing JavaScript code by simply doing that.

Resources

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s