Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
31178 tejbeer 1
/**
2
 * Fairly simply, this plug-in will take the data from an API result set
3
 * and sum it, returning the summed value. The data can come from any data
4
 * source, including column data, cells or rows.
5
 *
6
 * Note that it will attempt to 'deformat' any string based data that is passed
7
 * into it - i.e. it will strip any non-numeric characters in order to make a
8
 * best effort attempt to sum all data types. This can be useful when working
9
 * with formatting numbers such as currency. However the trade-off is that no
10
 * error is thrown if non-numeric data is passed in. You should be aware of this
11
 * in case unexpected values are returned - likely the input data is not what is
12
 * expected.
13
 *
14
 *  @name sum()
15
 *  @summary Sum the values in a data set.
16
 *  @author [Allan Jardine](http://sprymedia.co.uk)
17
 *  @requires DataTables 1.10+
18
 *
19
 *  @returns {Number} Summed value
20
 *
21
 *  @example
22
 *    // Simply get the sum of a column
23
 *    var table = $('#example').DataTable();
24
 *    table.column( 3 ).data().sum();
25
 *
26
 *  @example
27
 *    // Insert the sum of a column into the columns footer, for the visible
28
 *    // data on each draw
29
 *    $('#example').DataTable( {
30
 *      drawCallback: function () {
31
 *        var api = this.api();
32
 *        $( api.table().footer() ).html(
33
 *          api.column( 4, {page:'current'} ).data().sum()
34
 *        );
35
 *      }
36
 *    } );
37
 */
38
 
39
jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
40
	return this.flatten().reduce( function ( a, b ) {
41
		if ( typeof a === 'string' ) {
42
			a = a.replace(/[^\d.-]/g, '') * 1;
43
		}
44
		if ( typeof b === 'string' ) {
45
			b = b.replace(/[^\d.-]/g, '') * 1;
46
		}
47
 
48
		return a + b;
49
	}, 0 );
50
} );