forked from Rotifer/GoogleSpreadsheetProgramming_2015
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch03.gs
373 lines (355 loc) · 7.87 KB
/
ch03.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Code Example 3.1
/**
* Simple function that cannot be called from
* the spreadsheet as a user-defined function
* because it sets a spreadsheet property.
*
* @param {String} rangeAddress
* @return {undefined}
*/
function setRangeFontBold (rangeAddress) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(rangeAddress).setFontWeight('bold');
}
// Code Example 3.2
/**
* A function that demonstrates that function "setRangeFontBold()
* is valid although it cannot be called as a user-defined function.
*
* @return {undefined}
*/
function call_setCellFontBold () {
var ui = SpreadsheetApp.getUi(),
response = ui.prompt(
'Set Range Font Bold',
'Provide a range address',
ui.ButtonSet.OK_CANCEL),
rangeAddress = response.getResponseText();
setRangeFontBold(rangeAddress);
}
// Code Example 3.3
/**
* Function to demonstrate how to check
* the number and types of passed arguments.
*
*
* @return {undefined}
*/
function testFunc(arg1, arg2) {
var i;
Logger.log('Number of arguments given: ' +
arguments.length);
Logger.log('Number of arguments expected: ' +
testFunc.length);
for (i = 0; i< arguments.length; i += 1) {
Logger.log('The type of argument number ' +
(i + 1) + ' is ' +
typeof arguments[i]);
}
}
/**
* Function that calls "testFunc()"
* twice with different argument types
* and different argument counts.
*
* @return {undefined}
*/
function call_testFunc() {
Logger.log('First Invocation:');
testFunc('arg1', 2);
Logger.log('Second Invocation:');
testFunc('arg1', 2, 'arg3', false, new Date(), null, undefined);
}
// Code Example 3.4
// Function that is expected
// to add numbers but will also
// "add" strings.
function adder(a, b) {
return a + b;
}
// Test "adder()" with numeric arguments
// and with one numeric and one string
// argument.
function run_adder() {
Logger.log(adder(1, 2));
Logger.log(adder('cat', 1));
}
// Code Example 3.5
// Function that checks that
// both arguments are of type number.
// Throws an error if this is not true.
function adder(a, b) {
if (!(typeof a === 'number' &&
typeof b === 'number')) {
throw TypeError(
'TypeError: Both arguments must be numeric!');
}
return a + b;
}
// Test "adder()" with numeric arguments
// Thrown error is caught, see logger.
function run_adder() {
Logger.log(adder(1, 2));
try {
Logger.log(adder('cat', 1));
} catch (error) {
Logger.log(error.message);
}
}
// Code Example 3.6
/*
RSD Data (Paste this into a Google Sheet to test):
19.81
18.29
21.47
22.54
20.17
20.1
17.61
20.91
21.62
19.17
*/
/**
* Given the man and standard deviation
* return the relative standard deviation.
*
* @param {number} stdev
* @param {number} mean
* @return {number}
* @customfunction
*/
function RSD (stdev, mean) {
return 100 * (stdev/mean);
}
// Code Example 3.7
/**
* Given a temperature in Celsius, return Fahrenheit value.
* @param {number} celsius
* @return {number}
* @customfunction
*/
function CELSIUSTOFAHRENHEIT(celsius) {
if (typeof celsius !== 'number') {
throw TypeError('Celsius value must be a number');
}
return ((celsius * 9) / 5) + 32;
}
// Code Example 3.8
/**
* Given the radius, return the area of the circle.
* @param {number} radius
* @return {number}
* @customfunction
*/
function AREAOFCIRCLE (radius) {
if (typeof radius !== 'number' || radius < 0){
throw Error('Radius must be a positive number');
}
return Math.PI * (radius * radius);
}
// Code Example 3.9
/**
* Given a date, return the name of the day for that date.
*
* @param {Date} date
* @return {String}
* @customfunction
*/
function DAYNAME(date) {
var dayNumberNameMap = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'},
dayName,
dayNumber;
if(! date.getDay ) {
throw TypeError('TypeError: Argument is not of type "Date"!');
}
dayNumber = date.getDay();
dayName = dayNumberNameMap[dayNumber];
return dayName;
}
// Code Example 3.10
/**
* Add a given number of days to the given date
* and return the new date.
*
* @param {Date} date
* @param {number} days
* @return {Date}
*/
function addDays(date, days) {
// Taken from Stackoverflow:
// http://stackoverflow.com/questions/563406/add-days-to-datetime
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
/**
* Given a start date, an end date and a day name.
* return an array of all dates that fall (inclusive)
* between those two dates for the given day name.
*
* @param {Date} startDate
* @param {Date} endDate
* @param {String} dayName
* @return {Date[]}
* @customfunction
*/
function DATESOFDAY(startDate, endDate, dayName) {
var dayNameDates = [],
testDate = startDate,
testDayName;
while(testDate <= endDate) {
testDayName = DAYNAME(testDate);
if(testDayName.toLowerCase() === dayName.toLowerCase()) {
dayNameDates.push(testDate);
}
testDate = addDays(testDate, 1);
}
return dayNameDates;
}
// Code Example 3.11
/**
* Print all string properties to the
* Script Editor Logger
* @return {undefined}
*/
function printStringMethods() {
var strMethods =
Object.getOwnPropertyNames(String.prototype);
Logger.log('String has ' +
strMethods.length +
' properties.');
Logger.log(strMethods.sort().join('\n'));
}
// Code Example 3.12
/**
* Given a string, return a new string
* with the characters in reverse order.
*
* @param {String} str
* @return {String}
* @customfunction
*/
function REVERSESTRING(str) {
var strReversed = '',
lastCharIndex = str.length - 1,
i;
for (i = lastCharIndex; i >= 0; i -= 1) {
strReversed += str[i];
}
return strReversed;
}
// Code Example 3.13
/**
* Simulate a throw of a die
* by returning a number between
* and 6.
*
* @return {number}
* @customfunction
*/
function THROWDIE() {
return 1 + Math.floor(Math.random() * 6);
}
// Code Example 3.14
/** Concatenate cell values from
* an input range.
* Single quotes around concatenated
* elements are optional.
*
* @param {String[]} inputFromRng
* @param {String} concatStr
* @param {Boolean} addSingleQuotes
* @return {String}
* @customfunction
*/
function CONCATRANGE(inputFromRng, concatStr,
addSingleQuotes) {
var cellValues;
if (addSingleQuotes) {
cellValues =
inputFromRng.map(
function (element) {
return "'" + element + "'";
});
return cellValues.join(concatStr);
}
return inputFromRng.join(concatStr);
}
// Code Example 3.15
/**
* Return the ID of the active
* spreadsheet.
*
* @return {String}
* @customfunction
*/
function GETSPREADSHEETID() {
return SpreadsheetApp
.getActiveSpreadsheet().getId();
}
/**
Return the URL of the active
* spreadsheet.
*
* @return {String}
* @customfunction
*/
function GETSPREADSHEETURL() {
return SpreadsheetApp
.getActiveSpreadsheet().getUrl();
}
/**
Return the owner of the active
* spreadsheet.
*
* @return {String}
* @customfunction
*/
function GETSPREADSHEETOWNER() {
return SpreadsheetApp
.getActiveSpreadsheet().getOwner();
}
/**
Return the viewers of the active
* spreadsheet.
*
* @return {String}
* @customfunction
*/
function GETSPREADSHEETVIEWERS() {
var ss =
SpreadsheetApp.getActiveSpreadsheet();
return ss.getViewers().join(', ');
}
/**
Return the locale of the active
* spreadsheet.
*
* @return {String}
* @customfunction
*/
function GETSPREADSHEETLOCALE() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
return ss.getSpreadsheetLocale();
}
// Code Example 3.16
/**
* Return French version
* of English input.
*
* @param {String} input
* @return {String}
* @customfunction
*/
function ENGLISHTOFRENCH(input) {
return LanguageApp
.translate(input, 'en', 'fr');
}