Nate Woods

Nate Woods

Snippets

Some random bits of code that I have found useful or interesting over the years; Hopefully it will be helpful for you as well.


javascript array

JavaScript array item removal

A common problem I run into when coding is dealing with the limited object types of a particular language. Hopefully a yearly compilation of all these snippets can provide a script that expands languages to what they should have had in the first place.

 Array.prototype.remove = function(item) {
    var i = this.indexOf(item);
    if (i!=-1) this.splice(i, 1);
};
Published: continue reading »

javascript array

Javascript Array Random

Another worthy one for the notebooks, the random entry of an array!

Array.prototype.random = function() {
    return this[Math.floor(Math.random()*this.length)];
};
Published: continue reading »

javascript array

JavaScript array sum and average

I can’t take credit from this one, but I think the guys at Hummingbird had something right with their recursive sum function for arrays. This function simply sums the numbers in an array.

Array.prototype.sum = function() {
  return (! this.length) ? 0 : this.slice(1).sum() +
    ((typeof this[0] == 'number') ? this[0] : 0);
};
Published: continue reading »

javascript date

JavaScript format date

Humminbird and their helpers.js file, where they add a simple time formatting function to their Date object.

Date.prototype.formattedTime = function() {
  var formattedDate = this.getHours();

  var minutes = this.getMinutes();
  if(minutes > 9) {
    formattedDate += ":" + minutes;
  } else {
    formattedDate += ":0" + minutes;
  }

  var seconds = this.getSeconds();
  if(seconds > 9) {
    formattedDate += ":" + seconds;
  } else {
    formattedDate += ":0" + seconds;
  }

  return formattedDate;
};
Published: continue reading »

javascript string

JavaScript Repeat a string

After writing writing my fair share of for-loops, I decided there must be a better way to repeat a string.  Personally, I found this solution to be very elegant and hopefully will help you as much as it helped me.

String.prototype.repeat = function(n) {
     return new Array(1 + n).join(this);
}
Published: continue reading »

javascript array

JavaScript Array Contains

Here is a quick one for you today.  Ever just want a simple way to see if there is an item in an array?  Well fear not, this little snippet is to the rescue!

Array.prototype.contains = function(x) {
    return (this.indexOf(x) > -1);
}
Published: continue reading »

×