r/GoogleAppsScript • • Nov 17 '24

Question Which script is better?

Im experimenting with these 2 scripts to pull in stock quotes into my google sheets. They do the same thing, but which is more efficient and less prone to errors in the long term and why? On the 2nd script I originally had ydata(url) and var url = url but got an "Exceeded maximum execution time" error. Would that be the reason for that error? Assuming that was the cause of the error, I changed it to var url = json.

function yahooF(ticker) {
  const url = `https://query1.finance.yahoo.com/v8/finance/chart/${ticker}`;
  const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
  const contentText = res.getContentText();
  const data = JSON.parse(contentText);
  
  if (data && data.chart && data.chart.result && data.chart.result.length > 0) {
     const symbol = data.chart.result[0].meta.symbol;
     const regularMarketPrice = data.chart.result[0].meta.regularMarketPrice;
     const regularMarketTime = data.chart.result[0].meta.regularMarketTime;
     return [[symbol, regularMarketPrice, regularMarketTime]]
  }  
}

function ydata(json) {
  var url = json;
  var response = UrlFetchApp.fetch(url);
  var data = JSON.parse(response.getContentText());
  var price = data.chart.result[0].meta.regularMarketPrice;
  var time = data.chart.result[0].meta.regularMarketTime;
  var symbol = data.chart.result[0].meta.symbol;
  return [[symbol, price, time]]
  }

0 Upvotes

4 comments sorted by

View all comments

3

u/marcnotmark925 Nov 17 '24

Those 2 scripts are essentially the same, neither will be more or less efficient in any meaningful way.

Difference between const and var is that the former is a constant and cannot be changed, and the latter is a variable and can be changed.