forked from jc324x/google-apps-script-cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
2378 lines (1995 loc) · 59.7 KB
/
main.js
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function test() {}
Logger.log("Start");
// | General
// | - Array
// | -- Check for a Value
// | -- Remove Duplicates
// | -- Remove Empty Elements
// | -- Get Count of Values
// | -- Intersect of Two Arrays
// | -- Compare Two Arrays
// | -- Array as Delimited String
// | -- Array as Modified Delimited String
// | - Two-Dimensional Array
// | -- Flatten Two-Dimensional Array
// | - Array of Objects
// | -- Sort by Property or Properties
// | -- Find Object With Unique Property Value
// | -- Find Earliest or Latest Object by Timestamp
// | -- Filter by Property Value or Values
// | -- Unify Properties for Array of Objects
// | - Object
// | -- Array of Matching Property Values
// | -- Merge Objects
// | - Dates and Times
// | -- Formatted Timestamps
// | -- Date Object from String
// | -- Match a Date to a Date Range
// | Drive
// | - Folders
// | -- Create or Verify Folder Path
// | -- Last Folder in Folder Path
// | -- Array of All Folders
// | --- All Folders in a Folder
// | --- All Folders at Root
// | --- All Folders in Drive
// | -- Array of All Folder Names
// | -- Find a Folder
// | --- Find a Folder in a Folder
// | --- Find a Folder at Root
// | --- Find a Folder in Drive
// | -- Create or Verify Folders
// | --- Create or Verify Folders in a Folder
// | --- Create or Verify Folders at Root
// | - Files
// | -- Array of All Files
// | --- All Files in a Folder
// | --- All Files at Root
// | --- All Files in Drive
// | -- Array of All File Names
// | -- Find a File
// | --- Find a File in a Folder
// | --- Find a File at Root
// | --- Find a File in Drive
// | --- Find a File at Path
// | -- Copy a File to a Folder
// | -- Move a File to a Folder
// | - Files and Folders
// | -- Rename a File or Folder
// | -- Parent Folder of a File or Folder
// | - JSON
// | -- Object From URL
// | -- Object From File
// | -- Object From URL or File
// | Sheets
// | - Managing Spreadsheet Files
// | -- Create or Verify Spreadsheet
// | --- Create or Verify Spreadsheet in a Folder
// | --- Create or Verify Spreadsheet at Root
// | -- Id of Active Spreadsheet
// | -- Open File as Spreadsheet
// | - Utility Functions for Sheets
// | -- Convert Column Number to a Letter
// | -- Convert Column Letter to a Number
// | -- Replicating Import Range
// | -- Evaluating True and False
// | - Object
// | -- Object from Range
// | - Array of Objects
// | -- Utility Functions for Array of Objects
// | --- Header Range
// | --- Value Range
// | --- Header Values
// | --- Values by Row
// | -- Array of Objects from Sheet
// | -- Array of Objects from Range
// | - Array
// | -- Array of Values for Column
// | --- For Header Value
// | --- For Column Number
// | --- For Range Object
// | Docs
// | - Managing Document Files
// | -- Create or Verify Document
// | --- Create or Verify Document in a Folder
// | --- Create or Verify Document at Root
// | -- Id of Active Document
// | -- Open File as Document
// | - Utility Functions for Docs
// | -- Access Document Body
// | -- Clear Document Body
// | Merges
// | - Sheets and Docs
// | -- String From Object Properties
// | -- Replace Object Properties
// | --- Replace Object Properties in Document
// | --- Replace Object Properties in Spreadsheet
// | --- Replace Object Properties in Sheet
// | -- Copy Template for Item in Array of Objects and Replace Object Properties
// | --- Copy Document Template and Replace Object Properties
// | --- Copy Spreadsheet Template and Replace Object Properties
// | -- Cell Shading
// | --- Index Object Properties
// | -- Create Bulleted List in Document for Array of Objects
// | --- Single Division List
// | --- Multi Division List
// | - Gmail
// | -- Mail Merge
// | --- Append Body Property for Object in Array of Objects
// | --- Run Mail Merge for Array of Objects
// Future Additions:
// * Timestamp on Cell Change
// * Copy Formulas Down
// * Create Multidimensional Array of Values
// * Convert JSON to Sheet
// * 5 Minute Timer Management
// * Shade Cells in Document Tables and Spreadsheets
// Possible Additions:
// * Multidimensional Array from Array of Objects
// * Count of Value in Array of Objects
// * Recursive Moving / Copying Folders
// General
// - Array
// -- Check for a Value
/**
* Returns true if the value is in the array.
*
* @param {Array} arr
* @param {*} val
* @returns {boolean}
*/
function checkValIn(arr, val) {
return arr.indexOf(val) > -1;
}
// var arr_cvi = [1, 2, 3, 4];
// Logger.log(checkValIn(arr_cvi, 5)); // false
// -- Remove Duplicates
/**
* Returns an array with no duplicate values.
*
* @param {Array} arr
* @returns {Array}
*/
function rmDuplicatesFrom(arr) {
var check = {};
var result = [];
var j = 0;
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(check[item] !== 1) {
check[item] = 1;
result[j++] = item;
}
}
return result;
}
// var arr_rdf = [1, 2, 3, 1, 2, 3, 4,];
// Logger.log(rmDuplicatesFrom(arr_rdf)); // [1, 2, 3, 4]
// -- Remove Empty Elements
/**
* Returns an array with no empty elements.
*
* @param {*} x
* @returns {Array}
*/
function rmEmptyEl(x) {
return (x !== (undefined || ''));
}
// var arr_rev = ["a",,"b",,,"c"];
// Logger.log(arr_rev.filter(rmEmptyEl)); // ["a", "b", "c"]
// -- Get Count of Values
/**
* Returns an array of objects. Objects have two properties, count and value.
*
* @param {Array} arr
* @property {value} a value found in the array
* @property {count} count of the value in the array
* @returns {Object[]}
*/
function countOfValIn(arr) {
var result = [];
var copy = arr.slice(0);
for (var i = 0; i < arr.length; i++) {
var myCount = 0;
for (var w = 0; w < copy.length; w++) {
if (arr[i] == copy[w]) {
myCount++;
delete copy[w];
}
}
if (myCount > 0) {
var obj = {};
obj.value = arr[i];
obj.count = myCount;
result.push(obj);
}
}
return result;
}
// var arr_covi = ["a", "b", "c", "a", "b", "c", "a"];
// Logger.log(countOfValIn(arr_covi)); // [{count=3.0, value=a}, {count=2.0, value=b}, {count=2.0, value=c}]
// -- Intersect of Two Arrays
/**
* Returns an array of the elements in both arrays.
*
* @param {Array} arrA
* @param {Array} arrB
* @returns {Array}
*/
function intersectOf(arrA, arrB) {
var a = 0;
var b = 0;
var result = [];
while( a < arrA.length && b < arrB.length ) {
if (arrA[a] < arrB[b] ) { a++; }
else if (arrA[a] > arrB[b] ) { b++; }
else {
result.push(arrA[a]);
a++;
b++;
}
}
return result;
}
// var arrA_io = [1, 2, 3];
// var arrB_io = [3, 4, 5];
// Logger.log(intersectOf(arrA_io, arrB_io)); // [3]
// -- Compare Two Arrays
/**
* Returns true if both arrays have the same elements in the same order.
*
* @param {Array} arrA
* @param {Array} arrB
* @returns {boolean}
*/
function compareArr(arrA, arrB) {
if(arrA.length !== arrB.length) return false;
for(var i = arrA.length; i--;) {
if(arrA[i] !== arrB[i]) return false;
}
return true;
}
// var arrA_ca = [1, 2, 3, 4, 5];
// var arrB_ca = [1, 2, 3, 4, 5];
// var arrC_ca = ["a", "b", "c", "d", "e"];
// Logger.log(compareArr(arrA_ca, arrB_ca)); // true
// Logger.log(compareArr(arrA_ca, arrC_ca)); // false
// -- Array as Delimited String
/**
* Returns a string of array values.
* Elements are separated by a delimiter and a space.
*
* @param {Array} arr
* @param {string} delim
* @returns {string}
*/
function delimStrFromArr(arr, delim) {
var _arr = rmDuplicatesFrom(arr).sort();
var result = "";
for (var i = 0; i < _arr.length; i++) {
result += _arr[i] + delim + " ";
}
result = result.slice(0, -2);
return result;
}
// var arr_da = ["c@example.com", "b@example.com", "a@example.com"];
// Logger.log(delimStrFromArr(arr_da, ",")); // "a@example.com, b@example.com, c@example.com"
// -- Array as Modified Delimited String
/**
* Returns a string of array values.
* Elements are separated by a delimiter and a space, each followed by a modification.
*
* @param {Array} arr
* @param {string} delim
* @param {string} mod Modification to append to each item in the array.
* @returns {string}
*/
function delimStrFromArrMod(arr, delim, mod) {
var _arr = rmDuplicatesFrom(arr).sort();
var result = "";
for (var i = 0; i < _arr.length; i++) {
result += _arr[i] + mod + delim + " ";
}
result = result.slice(0, -2);
return result;
}
// var arr_clfd = ["x", "z", "y"];
// Logger.log(delimStrFromArrMod(arr_clfd, ",", "@example.com")); // "x@example.com, y@example.com, z@example.com"
// - Two-Dimensional Array
// -- Flatten Two-Dimensional Array
/**
* Returns an array containing all values in a two-dimensional array.
*
* @param {Array[]} twoDArr
* @returns {Array}
*/
function flattenTwoDArr(twoDArr) {
var result = twoDArr.reduce(function(a, b) {
return a.concat(b);
});
return result;
}
// var sheet_fma = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
// var val_fma = sheet_fma.getRange("G2:H5").getValues();
// Logger.log(flattenTwoDArr(val_fma).sort()); // [1, 2, 3, 4, 5, 6, 7, 8]
// - Array of Objects
var ex_arrObj = [
{a: 1000, b: 1, c: 5},
{a: 10000, b: 2, c: 5000},
{a: 10, b: 2, c: 500},
{a: 1, b: 1, c: 50}
];
// -- Sort by Property or Properties
/**
* Returns an array of objects sorted by a single property value.
*
* @param {string} prop
* @returns {Object[]}
*/
function dynSort(prop) {
var sortOrder = 1;
if(prop[0] === "-") {
sortOrder = -1;
prop = prop.substr(1);
}
return function (a,b) {
var result = (a[prop] < b[prop]) ? -1 : (a[prop] > b[prop]) ? 1 : 0;
return result * sortOrder;
};
}
// Logger.log(ex_arrObj.sort(dynSort("a")));
// [{a=1.0, b=1.0, c=50.0}, {a=10.0, b=2.0, c=500.0}, {a=1000.0, b=1.0, c=5.0}, {a=10000.0, b=2.0, c=5000.0}]
/**
* Returns an array of objects sorted by multiple property values.
* @param {...string}
* @returns {Object[]}
*/
function dynSortM() {
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
while(result === 0 && i < numberOfProperties) {
result = dynSort(props[i])(obj1, obj2);
i++;
}
return result;
};
}
// Logger.log(ex_/rrObj.sort(dynSortM("b", "c")));
// [{a=1000.0, b=1.0, c=5.0}, {a=1.0, b=1.0, c=50.0}, {a=10.0, b=2.0, c=500.0}, {a=10000.0, b=2.0, c=5000.0}]
// -- Find Object With Unique Property Value
/**
* Returns the first object in an array of objects with the key value pair.
*
* @param {Object[]} arrObj
* @param {string} pQuery
* @param {string} val
* @returns {Object}
*/
function findObjIn(arrObj, pQuery, val) {
for (var i = 0; i < arrObj.length; i++) {
var obj = arrObj[i];
for (var prop in obj) {
if (obj.hasOwnProperty(pQuery) && prop == pQuery && obj[prop] == val) {
return obj;
}
}
}
}
// Logger.log(findObjIn(ex_arrObj,"a",1000)); // {a=1000.0, b=1.0, c=5.0}
/**
* Returns a value from the first matching object in the array.
*
* @param {Object[]} arrObj
* @param {string} pQuery
* @param {string} val
* @param {string} pReturn
* @returns {*}
*/
function findObjValIn(arrObj, pQuery, val, pReturn) {
for (var i = 0; i < arrObj.length; i++) {
var obj = arrObj[i];
for (var prop in obj) {
if (obj.hasOwnProperty(pQuery) && prop == pQuery && obj[prop] == val) {
return obj[pReturn];
}
}
}
}
// Logger.log(findObjValIn(ex_arrObj, "c", 500, "a")); // 10
// -- Find Earliest or Latest Object by Timestamp
/**
* Returns the object with the oldest Timestamp value.
*
* @param {Object[]} arrObj
* @returns {Object}
*/
function earliestTS(arrObj){
if (arrObj.length >= 2) {
var sorted = arrObj.sort(function(a,b){
return new Date(a.Timestamp) - new Date(b.Timestamp);
});
return sorted[0];
} else {
return arrObj[0];
}
}
// var sheet_fe = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
// var arrObj_fe = arrObjFromRange(sheet_fe, "J1:K4");
// Logger.log(earliestTS(arrObj_fe)); // {Timestamp=Sun Feb 19 19:43:40 GMT-06:00 2017, Multiple Choice=A}
/**
* Returns the object with the latest Timestamp value.
*
* @param {Object[]} arrObj
* @returns {Object}
*/
function latestTS(arrObj) {
if (arrObj.length >= 2) {
var sorted = arrObj.sort(function(a,b){
return new Date(b.Timestamp) - new Date(a.Timestamp);
});
return sorted[0];
} else {
return arrObj[0];
}
}
// var sheet_le = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
// var arrObj_le = arrObjFromRange(sheet_le, "J1:K4");
// Logger.log(latestTS(arrObj_le)); // {Timestamp=Wed Feb 22 19:45:07 GMT-06:00 2017, Multiple Choice=C}
// -- Filter by Property Value or Values
/**
* Returns an array of objects containing matching objects.
*
* @param {Object} arrObj
* @param {string} pQuery
* @param {string[]} arrVal
* @returns {Object[]}
*/
function filterObjIn(arrObj, pQuery, arrVal) {
var result = [];
for (var i = 0; i < arrVal.length; i++) {
var val = arrVal[i];
for (var j = 0; j < arrObj.length; j++) {
if (arrObj[j][pQuery] == val) result.push(arrObj[j]);
}
}
return result;
}
// Logger.log(filterObjIn(ex_arrObj, "a", [10])); // [{a=10.0, b=2.0, c=500.0}]
// Logger.log(filterObjIn(ex_arrObj, "c", [5, 500])); // [{a=1000.0, b=1.0, c=5.0}, {a=10.0, b=2.0, c=500.0}]
// -- Unify Properties for Array of Objects
/**
* Returns an array of objects, with an additional property value added to each matching object.
*
* @param {Object[]} arrObj
* @param {string[]} arrProp
* @param {string} newProp
* @returns {Object[]}
*/
function unifyPropForArrObj(arrObj, arrProp, newProp){
for (var i = 0; i < arrObj.length; i++){
var obj = arrObj[i];
for (var h = 0; h < arrProp.length; h++) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && prop == arrProp[h] && obj[prop] !== ""){
obj[newProp] = obj[prop];
}
}
}
}
return arrObj;
}
var arrObj_upfao = [
{x: 123},
{y: 234},
{z: 345},
];
// Logger.log(unifyPropForArrObj(arrObj_upfao, ["x","y","z"], "new"));
// [{new=123.0, x=123.0}, {new=234.0, y=234.0}, {new=345.0, z=345.0}]
// - Object
// -- Array of Matching Property Values
/**
* Returns an array of matching properties.
*
* @requires intersectOf()
* @param {Object} obj
* @param {string[]} props
* @returns {Array}
*/
function filterValIn(obj, props) {
var result = [];
var keys = intersectOf(Object.keys(obj), props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
for (var prop in obj) {
if (obj.hasOwnProperty(key)) {
result.push(obj[key]);
break;
}
}
}
return result;
}
// var obj_fvi = {
// a: 1,
// b: 2,
// c: 3
// };
// var arr_fvi = ["a", "b", "d"];
// Logger.log(filterValIn(obj_fvi, arr_fvi)); // [1, 2]
// Merge Objects
/**
* Returns an object with the values of the argument objects.
* If multiple objects have the same property value, the last value set is retained.
* @param {...Object}
* @returns {Object}
*/
function mergeObjs() {
var obj = arguments[0];
for (i = 1; i < arguments.length; i++) {
var src = arguments[i];
for (var key in src) {
if (src.hasOwnProperty(key)) obj[key] = src[key];
}
}
return obj;
}
// var objA_mo = {
// a: 1,
// b: 2,
// c: 3
// };
// var objB_mo = {
// c: 4,
// d: 5,
// e: 6,
// f: 7
// };
// Logger.log(mergeObjs(objA_mo, objB_mo)); // {a=1.0, b=2.0, c=4.0, d=5.0, e=6.0, f=7.0}
// - Dates and Times
// -- Formatted Timestamps
/**
* Returns a string of today's date formatted "month-day-year".
*
* @returns {string}
*/
function fmatD() {
var n = new Date();
var d = [ n.getMonth() + 1, n.getDate(), n.getYear() ];
return d.join("-");
}
// Logger.log(fmatD()); // "4-24-2017"
/**
* Returns a string of the current time formatted "hour:minute:second".
*
* @returns {string}
*/
function fmat24T(){
var n = new Date();
var t = [ n.getHours(), n.getMinutes(), n.getSeconds() ];
for ( var i = 1; i < 3; i++ ) {
if ( t[i] < 10 ) {
t[i] = "0" + t[i];
}
return t.join(":");
}
}
// Logger.log(fmat24T()); // "20:43:40"
/**
* Returns a string of today's date and the current time formatted "month-day-year hour:minute:second AM/PM"
*
* @returns {string}
*/
function fmat12DT() {
var n = new Date();
var d = [ n.getMonth() + 1, n.getDate(), n.getYear() ];
var t = [ n.getHours(), n.getMinutes(), n.getSeconds() ];
var s = ( t[0] < 12 ) ? "AM" : "PM";
t[0] = ( t[0] <= 12 ) ? t[0] : t[0] - 12;
for ( var i = 1; i < 3; i++ ) {
if ( t[i] < 10 ) {
t[i] = "0" + t[i];
}
}
return d.join("/") + " " + t.join(":") + " " + s;
}
// Logger.log(fmat12DT()); // "4-24-2017 8:43:40 PM"
// -- Date Object from String
/**
* Returns a new date object from a string formatted year-month-date.
*
* @param {string} str
* @returns {Date}
*/
function dateObjectFromString(str) {
var split = str.split("-");
var months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
return new Date (months[(split[1] - 1)] + " " + split[2] + ", " + split[0]);
}
// Logger.log(dateObjectFromString("2017-04-24")); // Mon Apr 24 00:00:00 GMT-05:00 2017
// -- Match a Date to Date Range
/**
* Returns a value associated with a date range.
*
* @param {Object[]} arrObj
* @param {string=new Date()} optDate - Date to match.
* @namespace
* @property {string} start - Starting date.
* @property {string} end - Ending date.
* @property {*} value - The value to return for a matching date.
* @returns {*}
*/
function matchDateRange(arrObj, optDate) {
var date = new Date();
if (optDate !== undefined) {
date = new Date(optDate);
}
for (i = 0; i < arrObj.length; i++) {
var start = new Date(arrObj[i].start);
var end = new Date(arrObj[i].end);
if (date >= start && date <= end ) {
return arrObj[i].value;
}
}
}
// var quarterDates = [
// {start: "08/01/2016", end: "10/28/2016", value: 1},
// {start: "11/02/2016", end: "01/09/2017", value: 2},
// {start: "01/15/2017", end: "03/19/2017", value: 3},
// {start: "03/21/2017", end: "06/15/2017", value: 4},
// {start: "06/16/2017", end: "07/30/2017", value: "summer vacation"}
// ];
// Logger.log(matchDateRange(quarterDates)); // "summer vacation" (06/25/2017)
// Logger.log(matchDateRange(quarterDates, "08/02/2016")); // 1
// Drive
// - Folders
// -- Create or Verify Folder Path
/**
* Returns a folder at the end of a folder path.
* The folder is created if it does not exist already.
*
* @param {string} path
* @returns {Folder}
*/
function createVerifyPath(path) {
var split = path.split('/');
var fldr;
for (i = 0; i < split.length; i++) {
var fi = DriveApp.getRootFolder().getFoldersByName(split[i]);
if (i === 0) {
if(!(fi.hasNext())) {
DriveApp.createFolder(split[i]);
fi = DriveApp.getFoldersByName(split[i]);
}
fldr = fi.next();
} else if (i >= 1) {
fi = fldr.getFoldersByName(split[i]);
if(!(fi.hasNext())) {
fldr.createFolder(split[i]);
fi = DriveApp.getFoldersByName(split[i]);
}
fldr = fi.next();
}
}
return fldr;
}
// Logger.log(createVerifyPath("google-apps-script-cheat-sheet-demo/folders/A/B/C")); // C
// -- Last Folder in Folder Path
/**
* Returns the last folder in a folder path.
*
* @param path
* @returns {Folder}
*/
function lastFolderIn(path) {
var fi;
var split = path.split('/');
var fldr;
for (i = 0; i < split.length; i++) {
if (i === 0) {
fi = DriveApp.getRootFolder().getFoldersByName(split[i]);
if (fi.hasNext()) {
fldr = fi.next();
}
} else if (i >= 1) {
fi = fldr.getFoldersByName(split[i]);
if (fi.hasNext()) {
fldr = fi.next();
}
}
}
return fldr;
}
// Logger.log(lastFolderIn("google-apps-script-cheat-sheet-demo/folders/A/B")); // B
// Logger.log(lastFolderIn("google-apps-script-cheat-sheet-demo/folders/A/B/C/D/E/F/G")); // C
// -- Array of All Folders
// --- All Folders in a Folder
/**
* Returns an array of all folders in a folder.
*
* @param {Folder} fldr
* @returns {Folder[]}
*/
function foldersIn(fldr) {
var fi = fldr.getFolders();
var arr = [];
while (fi.hasNext()) {
var _fldr = fi.next();
arr.push(_fldr);
}
return arr;
}
// Logger.log(foldersIn(lastFolderIn("google-apps-script-cheat-sheet-demo/folders/"))); // [A]
// --- All Folders at Root
/**
* Returns an array of all folders in the root of the user's Drive.
*
* @returns {Folder[]}
*/
function rootFolders() {
var rf = DriveApp.getRootFolder();
var fi = rf.getFolders();
var arr = [];
while (fi.hasNext()) {
var fldr = fi.next();
arr.push(fldr);
}
return arr;
}
// Logger.log(rootFolders());
// --- All Folders in Drive
/**
* Returns an array of all folders in the user's Drive.
*
* @returns {Folder[]}
*/
function allFolders() {
var fi = DriveApp.getFolders();
var arr = [];
while (fi.hasNext()) {
var fldr = fi.next();
arr.push(fldr);
}
return arr;
}
// Logger.log(allFolders());
// -- Array of Folder Names
/**
* Returns an array of folder names.
*
* @param {Folders[]}
* @returns {string[]}
*/
function folderNames(fldrs) {
var arr = [];
for (var i = 0; i < fldrs.length; i++) {
var name = fldrs[i].getName();
arr.push(name);
}
return arr;
}
// var arr_fn = foldersIn(lastFolderIn("google-apps-script-cheat-sheet-demo/folders/A/B"));
// Logger.log(folderNames(arr_fn)); // [C]
// -- Find a Folder
// --- Find a Folder in a Folder
/**
* Returns a folder.
*
* @requires foldersIn()
* @requires folderNames()
* @requires checkValIn()
* @param {Folder} fldr
* @param {string} name
* @returns {Folder}
*/
function findFolderIn(fldr, name) {
var fldrs = foldersIn(fldr);
var names = folderNames(fldrs);
if (checkValIn(names, name)) {
var _fldr = fldr.getFoldersByName(name).next();
return _fldr;
}
}
// var fldr_ffi = lastFolderIn("google-apps-script-cheat-sheet-demo/folders");
// Logger.log(findFolderIn(fldr_ffi, "A")); // A
// --- Find a Folder at Root
/**
* Returns a folder at the root of the user's Drive.
*
* @requires rootFolders()
* @requires folderNames()
* @requires checkValIn()
* @param {string} name
* @returns {Folder}
*/
function findFolderAtRoot(name) {
var rf = DriveApp.getRootFolder();
var fldrs = rootFolders();
var names = folderNames(fldrs);
if (checkValIn(names, name)) {
var fldr = rf.getFoldersByName(name).next();
return fldr;
}
}
// Logger.log(findFolderAtRoot("google-apps-script-cheat-sheet-demo")); // google-apps-script-cheat-sheet-demo
// --- Find a Folder in Drive
/**
* Returns the first matching folder in Drive.
*
* @param {string} name
* @returns {Folder}
*/
function findFolderInDrive(name) {
var fi = DriveApp.getFoldersByName(name);
while (fi.hasNext()){
var fldr = fi.next();
return fldr;
}
}
// Logger.log(findFolderInDrive("folders")); // folders
// -- Create or Verify Folders
// --- Create or Verify Folders in a Folder
/**
* Returns a folder.
* Creates folders within a folder if they don't already exist.
*
* @requires foldersIn()
* @requires folderNames()
* @requires checkValIn()
* @param {Folder} fldr
* @param {string[]} names
* @returns {Folder}
*/
function createVerifyFoldersIn(fldr, names) {
var fldrs = foldersIn(fldr);
var _names = folderNames(fldrs);
for (i = 0; i < names.length; i++) {
if (!(checkValIn(_names, names[i]))) {
fldr.createFolder(names[i]);