// See https://en.wikipedia.orghttps://wikifreehand.com/en/User:V111P/js/Sum_numbers
function sumSelectedNumbers() {
var lang = mw.config.get('wgContentLanguage');
var decimalMark = window.decimalMark || (lang == 'en' ? '.' : ',');
var reNonNumNonDecimalMark = new RegExp('', 'g');
var reNonCommon = new RegExp('');
function sumFields(str) { // \n or \t divided fields
var fields = str.split(//);
var textVal, numVal, expr = '', ignored = '', total = 0;
for (var i = 0; i < fields.length; i++) {
textVal = fields;
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')).after(' (<a target="_blank" href="//en.wikipedia.orghttps://wikifreehand.com/en/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');
});