Я написал пользовательскую функцию для Google Sheets в Apps Script.Цель состоит в том, чтобы иметь лист, который автоматически вычисляет, кто кому сколько должен (например, разделить счет).
Мой лист выглядит так:
![enter image description here](https://i.stack.imgur.com/eLZEZ.png)
Первый счет (Ресторан) должен быть разделен на все 5, а второй счет должен быть разделен на все 5, кроме Питера, потому что в B3 нет 0.
входные данные для моей функции скрипта приложения будут ячейками от B1 до F3 (таким образом, значения И имена).Функция отлично работает - она рассчитывает правильные результаты.Я открываю эту таблицу через браузер (sheet.google.com) И через приложение для телефона (Google Sheets).Однако на моем телефоне часто случается, что в ячейке результата (с формулой =calc_debt(B1:F3)
) отображается только "Loading ..."
.В чем проблема?
Для полноты, вот код пользовательской функции:
function calc_debt(input) {
var credit = [0, 0, 0, 0, 0]; // credit[0] = Peter, credit[1] = Mark ...
for (var i = 1; i < input.length; i++) { // starting at i = 1 to skip the first row, which is the names!
// first: calculate how much everybody has to pay
var sum = 0;
var people = 0;
for (var j = 0; j <= 4; j++) {
if (input[i][j] !== "") {
sum += input[i][j];
people += 1;
}
}
var avg_payment = sum / people;
// second: calculate who has payed too much or too little
for (var j = 0; j <= 4; j++) {
if (input[i][j] !== "") {
credit[j] += input[i][j] - avg_payment;
}
}
}
// this function is needed later
function test_zero (value) {
return value < 0.00001;
};
var res = ""; // this variable will contain the result string, something like "Peter to Mark: 13,8 | Katy to ..."
while (!credit.every(test_zero)) {
var lowest = credit.indexOf(Math.min.apply(null, credit)); // find the person with the lowest credit balance (will be minus!)
var highest = credit.indexOf(Math.max.apply(null, credit)); // find the person with the highest credit balance (will be plus!)
var exchange = Math.min(Math.abs(credit[lowest]), Math.abs(credit[highest])); // find out by how much we can equalize these two against each other
credit[lowest] += exchange;
credit[highest] -= exchange;
res += input[0][lowest] + " to " + input[0][highest] + ": " + exchange.toFixed(2) + " | "; // input[0] = the row with the names.
}
return res;
}