Clean JavaScript - Utilities

There are many different methods of creating clean Javascript. This post is just a simple way that I prefer to do it.

This is a Sac Rate Calculator that I wrote in JavaScript:

// Namespace to DevelopLive
DevelopLive = window.DevelopLive || {}

// Define Dive
DevelopLive.Dive = window.DevelopLive.Dive || {}

;(function () {
  $self = DevelopLive.Dive

  $self.calcSac = function (
    psiIn,
    psiOut,
    time,
    depth,
    tankVolume,
    tankWorkingPsi,
  ) {
    // calculate DAC
    var dac = (psiIn - psiOut) / time,
      // calculate SAC
      sac = dac / (depth / 33 + 1),
      // calculate RMV
      rmv = (sac * tankVolume) / tankWorkingPsi

    // return
    return rmv
  }
})()

Simply, I am creating a namespace and definition then defining a self-calling function. Within this self-calling function I am defining the method for calculating the SAC rate as basically a static method.

Now you can use some sort of JQuery to pass parameters in:

// standard jquery self-calling function
jQuery(function () {
  // get the elements
  var psiIn = $('#psiIn'),
    psiOut = $('#psiOut'),
    time = $('#time'),
    depth = $('#depth'),
    tankVolume = $('#tankVolume'),
    tankWorkingPsi = $('#tankWorkingPsi'),
    finalLabel = $('#rate'),
    submitButton = $('#submitQuery')

  // when you click the submit button
  submitButton.live('click', function () {
    // get the sac rate
    var final = DevelopLive.Dive.calcSac(
      psiIn.val(),
      psiOut.val(),
      time.val(),
      depth.val(),
      tankVolume.val(),
      tankWorkingPsi.val(),
    )

    // set the rate
    finalLabel.text(final)
  })
})

Happy Coding.