This repository has been archived on 2021-05-25. You can view files and clone it, but cannot push or open issues or pull requests.
pyRCV2/worker.js

69 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-10-18 03:25:41 +11:00
importScripts('http://peterolson.github.com/BigRational.js/BigInt_BigRat.min.js', 'https://cdn.jsdelivr.net/npm/big.js@6.0.0/big.min.js', 'bundle.js');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
onmessage = async function(evt) {
if (evt.data.numbers == 'native') {
py.pyRCV2.numbers.set_numclass(py.pyRCV2.numbers.Native);
}
if (evt.data.numbers == 'rational') {
py.pyRCV2.numbers.set_numclass(py.pyRCV2.numbers.Rational);
}
2020-10-18 03:25:41 +11:00
if (evt.data.numbers == 'fixed') {
py.pyRCV2.numbers.set_numclass(py.pyRCV2.numbers.Fixed);
}
let election = py.pyRCV2.blt.readBLT(evt.data.data);
postMessage({'type': 'init', 'election': {
'candidates': election.candidates.map(c => c.py_name)
}});
// Create counter
let counter = py.pyRCV2.method.STVCCounter.STVCCounter(election);
// Reset
let result = counter.reset();
postMessage({'type': 'result', 'result': {
'comment': result.comment,
'candidates': result.candidates.py_items().map(([c, cc]) => [c.py_name, {
'transfers': cc.transfers.pp(2),
'votes': cc.votes.pp(2),
'state': cc.state
}]),
'exhausted': {
'transfers': result.exhausted.transfers.pp(2),
'votes': result.exhausted.votes.pp(2)
},
2020-10-18 02:54:51 +11:00
'total': result.total.pp(2),
'quota': result.quota.pp(2)
}});
// Step election
while (true) {
//await sleep(1000);
result = counter.step();
if (py.isinstance(result, py.pyRCV2.model.CountCompleted)) {
postMessage({'type': 'done'});
break;
} else {
postMessage({'type': 'result', 'result': {
'comment': result.comment,
'candidates': result.candidates.py_items().map(([c, cc]) => [c.py_name, {
'transfers': cc.transfers.pp(2),
'votes': cc.votes.pp(2),
'state': cc.state
}]),
'exhausted': {
'transfers': result.exhausted.transfers.pp(2),
'votes': result.exhausted.votes.pp(2)
},
2020-10-18 02:54:51 +11:00
'total': result.total.pp(2),
'quota': result.quota.pp(2)
}});
}
}
}