Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'input.map' in google apps script (custom spreadsheet function) example?

I'm confused by this example from Google's Apps Script Guide. This function iterates over given range and performs a computation on each cell.

function DOUBLE(input) {

  if (input.map) {            // Test whether input is an array.
    return input.map(DOUBLE); // Recurse over array if so.
  } else {
    return input * 2;
  }

}

Things I don't understand:

  1. What object is the input in this function? typeof tells me it is a number, but shouldn't it be an array? It is after all a range of values (e.g. A2:B).
  2. What is the .map thing after the input variable? I cannot find it in the reference page. It is also not highlighted, as variables or functions are.
  3. The purpose of the conditional statement is unclear to me. Does return input.map(DOUBLE) mean "do whatever you find in the corresponding else statement over the whole array"? Why is it structured like so?

Any insights (or pointers to the right sources) much appreciated.

like image 386
jakub Avatar asked Apr 26 '26 10:04

jakub


1 Answers

This code is an example of using introspection to conditionally execute the code. if (input.map) will return truthy if input is an Array (and has a map function) and will return falsy in all other cases.

This code is therefore testing to see whether input is an Array and if not, it is treating it as a number, otherwise it is treating it as an Array.

You can see the definition of the map function on MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Best book to learn about JavaScript is "JavaScript the Good Parts" http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=sr_1_1?ie=UTF8&qid=1419857713&sr=8-1&keywords=javascript+the+good+parts

like image 80
unobf Avatar answered Apr 28 '26 03:04

unobf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!