Photo for Useful JavaScript Snippets

I can't remember everything so, I've posted a bunch of JavaScript snippets I constantly use and reference.

Self-Executing anonymous functions

(function(){
    // code in here
})();

Convert unix time stamp to a pretty value

 function timeStampConverter(UNIX_timestamp) {
      UNIX_timestamp = parseInt(UNIX_timestamp, 10);
      var a = new Date(UNIX_timestamp*1000);
      var year = a.getFullYear();
      var month = a.getMonth() + 1;
      var date = a.getDate()
      // var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
      // var prettyMonth = months[a.getMonth()];
      // var hour = a.getHours();
      // var min = a.getMinutes();
      // var sec = a.getSeconds();
      return month + '/' + date + '/' + year;
 }

Add a comma to a number

 function addComma(n) {
      return (n + "").replace(/(\d)(?=(\d{3})+(\.\d+|)\b)/g, "$1,");
 }

Get median from an array

 function getMedian(values) {
      values.sort( function(a,b) {return a - b;} );
      var half = Math.floor(values.length/2);
      if(values.length % 2) {
           return values[half];
      } else {
           return (values[half-1] + values[half]) / 2;
      }
 }

Get average from an Array

 function getAverage(values) {
      var av = 0;
      var cnt = 0;
      for (var i = 0; i < values.length; i++) {
           var e = +values[i];
           if(!e && values[i] !== 0 && values[i] !== '0'){
                e--;
           }
           if (values[i] == e) {
                av += e;
                cnt++;
           }
      }
      return av/cnt;
 }

Zoom google map in on a point (but not too far)

 function smartZoom() {
      // note: this.globalBounds is a class variable that is set somewhere in your code like so: this.globalBounds = new google.maps.LatLngBounds();
      // extend the bounds this.globalBounds.extend(new google.maps.LatLng(lat, lng));
      var sumA, sumB, extendPoint1, extendPoint2, minDistance = 0.004;
      if (!this.globalBounds.isEmpty()) {
           sumA = this.globalBounds.getNorthEast().lng() - this.globalBounds.getSouthWest().lng();
           sumB = this.globalBounds.getNorthEast().lat() - this.globalBounds.getSouthWest().lat();
           if((sumA < minDistance && sumA > -minDistance) && (sumB < minDistance && sumB > -minDistance)){
                extendPoint1 = new google.maps.LatLng(this.globalBounds.getNorthEast().lat() + minDistance, this.globalBounds.getNorthEast().lng() + minDistance);
                extendPoint2 = new google.maps.LatLng(this.globalBounds.getNorthEast().lat() - minDistance, this.globalBounds.getNorthEast().lng() - minDistance);
                this.globalBounds.extend(extendPoint1);
                this.globalBounds.extend(extendPoint2);
           }
           this.googleMap.fitBounds(this.globalBounds);
      }
 }

Parse a WKT Text string into a polygon array

 function parsePolyStrings(ps) {
      var i, j, lat, lng, tmp, tmpArr, tmpPoint, arr = [], m = ps.match(/\([^\(\)]+\)/g);
      if (m !== null) {
           for (i = 0; i < m.length; i++) {
                //match all numeric strings
                tmp = m[i].match(/-?\d+\.?\d*/g);
                if (tmp !== null) {
                     //convert all the coordinate sets in tmp from strings to Numbers and convert to LatLng objects
                     for (j = 0, tmpArr = []; j < tmp.length; j+=2) {
                          lat = Number(tmp[j + 1]);
                          lng = Number(tmp[j]);
                          tmpPoint = new google.maps.LatLng(lat, lng);
                          tmpArr.push(tmpPoint);
                     }
                     arr.push(tmpArr);
                }
           }
      }
      return arr;
 }
 var wkt_string = 'POLYGON((18.530159374334467 -33.997246540870272, 18.530171912097686 -33.997367753070058, 18.530229084488873 -33.99736364500437, 18.530216546649875 -33.997242431908163, 18.530159374334467 -33.997246540870272))';
 var points = parsePolyStrings(wkt_string);
 var poly = new google.maps.Polygon({
      paths: points,
      strokeColor: '#ffcc33',
      strokeOpacity: 0.8,
      strokeWeight: 1,
      fillColor: '#ffcc33',
      fillOpacity: 0.5
 });
 poly.setMap(map);

About The Author

James Olson

James is a graduate of the University of Colorado with a degree in business management. After college, he worked for a small advertising company that focused on the Real Estate Industry where his main focus was on web advertising and email campaigns.

In 2008, James joined booj as a member of the Deployment team and quickly moved through the ranks to become the lead front-end developer. In 2012, he was named the Director of Research & Development where he continues to push the envelope of new web technologies.



Similar Posts

Photo for Click Outside Element To Close

Click Outside Element To Close

Here is a little jQuery snippet that allows you to click/touch outside of an element to close it. ...

Photo for jQuery Plugin Boilerplate

jQuery Plugin Boilerplate

Below is a pretty powerful jQuery plugin boilerplate. Simply replace the "MyPluginObject" with your ...