Skip to content

Instantly share code, notes, and snippets.

@gjask
Last active August 3, 2018 12:57
Show Gist options
  • Save gjask/9e90f7c87c0cced6d086a8dc8bc55281 to your computer and use it in GitHub Desktop.
Save gjask/9e90f7c87c0cced6d086a8dc8bc55281 to your computer and use it in GitHub Desktop.
Google spreadsheet custom function settling up debts in group of people.
function SETTLE_UP(data) {
var min = 0;
var max = 0;
var debter = 0;
var crediter = 0;
var amount = 0;
var names = data[0];
var values = data[1];
for(var i=0; i < values.length; i++){
if (values[i] > max){
max = values[i];
debter = i;
}
if (values[i] < min){
min = values[i];
crediter = i;
}
}
if (max * min == 0){
return [];
}
min = Math.abs(min);
if (max > min){
amount = min;
} else {
amount = max;
}
values[crediter] += amount;
values[debter] -= amount;
var transactions = SETTLE_UP([names, values]);
transactions.unshift([names[debter], names[crediter], amount]);
return transactions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment