I'm confused by this example from Google's Apps Script Guide. This function iterates over given range and performs a putation 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:
- 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). - What is the
.map
thing after theinput
variable? I cannot find it in the reference page. It is also not highlighted, as variables or functions are. - The purpose of the conditional statement is unclear to me. Does
return input.map(DOUBLE)
mean "do whatever you find in the correspondingelse
statement over the whole array"? Why is it structured like so?
Any insights (or pointers to the right sources) much appreciated.
I'm confused by this example from Google's Apps Script Guide. This function iterates over given range and performs a putation 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:
- 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). - What is the
.map
thing after theinput
variable? I cannot find it in the reference page. It is also not highlighted, as variables or functions are. - The purpose of the conditional statement is unclear to me. Does
return input.map(DOUBLE)
mean "do whatever you find in the correspondingelse
statement over the whole array"? Why is it structured like so?
Any insights (or pointers to the right sources) much appreciated.
Share Improve this question asked Dec 29, 2014 at 12:45 jakubjakub 5,1444 gold badges32 silver badges49 bronze badges1 Answer
Reset to default 6This 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/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Best book to learn about JavaScript is "JavaScript the Good Parts" http://www.amazon./JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=sr_1_1?ie=UTF8&qid=1419857713&sr=8-1&keywords=javascript+the+good+parts