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:
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). .map thing after the input variable? I cannot find it in the reference page. It is also not highlighted, as variables or functions are.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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With