Last active
September 24, 2019 11:57
-
-
Save sujeetkv/da69ba85ba5e60a4ee2645daee750a39 to your computer and use it in GitHub Desktop.
jQuery plugin to get sum of selected input values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
/** | |
* jQuery plugin to get sum of selected input values | |
* Usage syntax: | |
* $('selector').sum() | |
* $('selector').sum(initial_value) | |
* $('selector').sum(parse_type) | |
* $('selector').sum(parse_type, initial_value) | |
*/ | |
$.fn.sum = function (parse_type, initial_value) { | |
var parseType = typeof parse_type === 'function' ? parse_type : parseFloat; | |
var initialValue = parseType(typeof parse_type !== 'function' ? parse_type : initial_value) || 0; | |
var mapper = function () { | |
return parseType($(this).val() || 0); | |
}; | |
var reducer = function (accumulator, currentValue) { | |
return accumulator + currentValue; | |
}; | |
return initialValue + this.map(mapper).get().reduce(reducer); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment