JSFiddle - React, Tailwind, and code Playground
by BurpmanJunior
HTML
<div id="calc">
<select class="cc-conf">
<option value="0,18000,45000|0,25,40">config 1</option>
<option value="0,12000,32000|0,15,31">config 2</option>
</select>
<input type="number" class="cc-input" min="0" step="1" value="0" />
<button class="cc-update">Update</button>
</div>
<div id="calc-output"></div>
JavaScript
/**
* Commission calculator
*/
var _cc = _cc || {
conf: {
b: [],
p: []
}
};
_cc.init = function (e, b, p) {
var e = document.getElementById(e);
if (!e) {
return false;
}
var ccConf = e.querySelectorAll('select.cc-conf')[0];
var ccInput = e.querySelectorAll('input.cc-input')[0];
var ccUpdate = e.querySelectorAll('button.cc-update')[0];
var outputElem = document.getElementById('calc-output');
_cc.getConf(ccConf);
ccConf.addEventListener('change', function (e) {
_cc.getConf(ccConf);
});
ccInput.addEventListener('keyup', function (e) {
if (e.keyCode == 13) {
outputElem.innerHTML = _cc.getVal(ccInput.value).toFixed(2);
}
});
ccUpdate.addEventListener('click', function () {
outputElem.innerHTML = _cc.getVal(ccInput.value).toFixed(2);
});
}
_cc.getConf = function (e) {
var v = e.value;
v = v.split('|');
var tb = v[0].split(','),
tp = v[1].split(','),
ob = [],
op = [];
for (var i = 0; i < tb.length; i++) {
ob.push(parseFloat(tb[i]));
}
_cc.conf.b = ob;
for (var i = 0; i < tp.length; i++) {
op.push(parseFloat(tp[i]));
}
_cc.conf.p = op;
return _cc.conf;
}
_cc.getVal = function (val) {
val = parseFloat(val);
if (val < 0 || isNaN(val)) {
return 0;
}
var b = _cc.conf.b,
p = _cc.conf.p,
v = 0;
if (b.length != p.length) {
return 'Error: Unmatched comparator lengths';
}
for (var i = 0; i < b.length; i++) {
if (val > b[i]) {
v += Math.min(val - b[i], b[i]) * (p[i] / 100);
}
}
return v;
}
_cc.init('calc');