Created
February 2, 2018 23:40
-
-
Save rafinskipg/6d2420a902cf01708cae9c9b7498d680 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const MAX_DEVIATION_SUPPORTED = 0.35 | |
function average(items) { | |
const total = items.reduce((prev, next) => { | |
return prev + next | |
}, 0) | |
return total / items.length | |
} | |
function calculate(votes) { | |
const candidates = {} | |
// Store the candidates | |
Object.keys(votes[0]).forEach((k) => { | |
const votesForK = votes.map(v => v[k]) | |
candidates[k] = average(votesForK) | |
}) | |
return candidates | |
} | |
function getDeviation(a, b) { | |
return Math.abs((a-b)/b) | |
} | |
// Check that a value is less than X percent different than other | |
function isInBoundaries(valueA, valueB) { | |
const deviation = getDeviation(valueA, valueB) | |
return deviation < MAX_DEVIATION_SUPPORTED | |
} | |
function getDeviations(result, votes) { | |
let deviations = {} | |
Object.keys(result).forEach(k => { | |
const votesForK = votes.map(v => v[k]) | |
deviations[k] = votesForK.map(v => getDeviation(v, result[k])) | |
}) | |
return deviations | |
} | |
function isValidResult(result, votes) { | |
let isValid = Object.keys(result).map((k) => { | |
const votesForK = votes.map(v => v[k]) | |
// Check | |
return votesForK.reduce((prev, next) => { | |
return prev && isInBoundaries(result[k], next) | |
}, true) | |
}) | |
.reduce((prev, next) => prev && next, true) | |
return isValid | |
} | |
function doTheThing(votes) { | |
const result = calculate(votes) | |
const isValid = isValidResult(result, votes) | |
console.log('-------TRYING CONSENSUS WITH', result) | |
if(!isValid) { | |
console.log('Is not valid', 'getting average deviations') | |
const deviations = getDeviations(result, votes) | |
console.log(deviations) | |
} else { | |
console.log('Congrats! Consensus reached') | |
} | |
} | |
const votesA = { | |
a: 33, | |
b: 33, | |
c: 33 | |
} | |
const votesB = { | |
a: 35, | |
b: 40, | |
c: 25 | |
} | |
const votesC = { | |
a: 40, | |
b: 40, | |
c: 20 | |
} | |
const votes = [votesA, votesB, votesC] | |
doTheThing(votes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment