Jump to content

User:V111P/js/SumNumbers.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// See https://en.wikipedia.org/wiki/User:V111P/js/Sum_numbers
function sumSelectedNumbers() {
	var lang = mw.config.get('wgContentLanguage');
	var decimalMark = window.decimalMark || (lang == 'en' ? '.' : ',');
	var reNonNumNonDecimalMark = new RegExp('[^0-9' + decimalMark + ']', 'g');
	var reNonCommon = new RegExp('[^0-9\s,' + decimalMark + ']');

	function sumFields(str) { // \n or \t divided fields
		var fields = str.split(/[\n\t]/);
		var textVal, numVal, expr = '', ignored = '', total = 0;
		for (var i = 0; i < fields.length; i++) {
			textVal = fields[i];
			if (textVal === '') continue;
			numVal = parseFloat(textVal.replace(reNonNumNonDecimalMark, '').replace(decimalMark, '.'));
			if (isNaN(numVal) || reNonCommon.test(textVal)) {
				ignored += textVal + ' | ';
				continue;
			}
			expr +=  (numVal + ' + ').replace('.', decimalMark);
			total += numVal;
		}
		return {total: total, expr: expr, ignored: ignored};
	}

	var total = 0, expr = '', ignored = '', r;
	if (window.getSelection) {
		var sel = window.getSelection();
		for (var i = 0; i < sel.rangeCount; i++) {
			r = sumFields(sel.getRangeAt(i).toString());
			total += r.total;
			expr += r.expr;
			ignored += r.ignored;
		}
	}

	var msg = '';
	total = ('' + total).replace('.', decimalMark);
	if (expr !== '' || ignored !== '')
		msg = expr.slice(0, -3) + ' = ' + total + (ignored ? '<br/>IGNORED: ' + ignored.slice(0, -3) : '');
	return msg;
}

function sumNumbersShowButtons() {
	var exist = $('.sumNumbersDiv');
	if (exist.length > 0)
		exist.remove();
	else {
		var div = $('<div class="sumNumbersDiv"><input class="sumNumbersButton" type="button" value="+"><div class="sumNumbers_msgDiv"></div></div>');
		$('h1,h2').after(div);
		$('table').after(div).before(div);
		$($('.sumNumbersButton')[0]).after(' (<a target="_blank"  href="//en.wikipedia.org/wiki/User:V111P/js/Sum_numbers">?</a>)');
		$('input.sumNumbersButton').click(function (e) {
			var msg = sumSelectedNumbers();
			if (console && console.log) console.log(msg);
			var t = $(e.target);
			$(e.target).parent().children('.sumNumbers_msgDiv').html(msg);
		});
	}
}

$(function () {
	mw.util.addPortletLink('p-tb', 'javascript:sumNumbersShowButtons()',
    'Sum numbers', 'sumNumbersToolbarLink',
	'Select some numbers on the page (in Firefox you can hold Ctrl to select multiple text ranges '
	+ 'and you can drag across table cells to select whole columns) '
	+ 'and press one of the + buttons to see the sum');
});