google-sheetsgoogle-apps-script

Google Sheets Run Library


I got a problems to run a library on google sheet.

this is my library. Actually I'm not sure if it is, I just typed out my code and deploy it as a library only. Is this considered a library? https://script.google.com/d/1caK6rW1--NmMSzSq0DHT0d4J-ucIdPv7KDPOmo16mZ9LBEZJo1OxXm8K/edit?usp=sharing

/**
 * Finds a combination of numbers that add up to a specific value.
 *
 * @param {A1:A16} data The range of cells containing the data.
 * @param {B1} target The target value.
 * @return An array containing the combination of values that add up to the target value.
 * @customfunction
 */
function findCombination(data, target) {
  var values = data;
  var n = values.length;
  var found = false;
  var result = [];
  
  for (var i = 1; i < Math.pow(2, n); i++) {
    var sum = 0;
    for (var j = 0; j < n; j++) {
      if ((i & (1 << j)) !== 0) {
        sum += values[j][0];
      }
    }
    
    if (sum === target) {
      result = values.map(function(value, index) {
        if ((i & (1 << index)) !== 0) {
          return value[0];
        } else {
          return "";
        }
      });
      found = true;
      break;
    }
  }
  
  if (!found) {
    result = ["No combination found"];
  }
  
  return result;
}

And then is this my code on google sheets,

function run(data, target) {

  Mylibrary.findCombination(data, target)

}

But when I type the run function in google sheet, it doesn't work very well. No error is being reported either, I don't understand how to improve it.

The purpose of this is to integrate all my scattered code into one library, and then other sheets call the lib for easy maintenance.


Solution

  • If your Google Apps Script project including run(data, target) correctly installs your script as a library, unfortunately, run(data, target) is not returned from Mylibrary.findCombination(data, target), because of no return. I think that this is the reason for your current issue. If my understanding is correct, please modify your showing script as follows.

    Modified script:

    function run(data, target) {
      return Mylibrary.findCombination(data, target);
    }
    

    Reference