Mansoor Elahi
Mansoor Elahi

Reputation: 959

Refactoring my coffeescript code to get sum of particular columns values

This may be an noob question , but I am an newbie in coffeescript and javascript , I am trying to figure out how can I refactor the below code to get sum of the values from two columns with different class names and display it in my html page here is the code what i have got so far:

totalItems = ->
  column= $("#websiteTable td[class=website_count]")
  theTotal = 0
  column.each ->
    value = $(this).html()
    theTotal += parseInt(value)
    return
  alert(theTotal)

newItems = ->
  column= $("#websiteTable td[class=new_count]")
  theTotal = 0
  column.each ->
    value = $(this).html()
    theTotal += parseInt(value)
    return
  alert(theTotal)

as you can see there is lot of repetitive code how effectively can I rewrite this ?

Thanks

Upvotes: 0

Views: 96

Answers (1)

Kyle Needham
Kyle Needham

Reputation: 3389

Create a function that takes a jQuery selector as a parameter.

calculateTotal = (element, total = 0) ->
    element.each ->
        value = $(@).html()
        total += +value

    total

Then you can do:

totalItems = calculateTotal $ "#websiteTable td[class=website_count]"
newItems = calculateTotal $ "#websiteTable td[class=new_count]"

See the live example below.

var calculateTotal;

calculateTotal = function(element, total) {
  if (total == null) {
    total = 0;
  }
  element.each(function() {
    var value;
    value = $(this).html();
    return total += +value;
  });
  
  return total;
};

$('button').on('click', function(){
	alert(calculateTotal($('ul li')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
	<li>2</li>
  	<li>4</li>
</ul>

<button>Calculate the total</button>

Upvotes: 3

Related Questions