-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
656 lines (581 loc) · 22 KB
/
index.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
// Code here is taken directly from: https://github.com/tlkiong/kiong.js/blob/master/index.js
(function() {
'use strict';
window.kiong = {
init: init,
removeTimezoneFromDate: removeTimezoneFromDate,
getMonthNameFromDateObj: getMonthNameFromDateObj,
// getDateInDDMMMMYYYY: getDateInDDMMMMYYYY,
// getMonthNameFromEpochDate: getMonthNameFromEpochDate,
// getDayInEpoch: getDayInEpoch,
isObjPresent: isObjPresent,
getObjType: getObjType,
getUUID: getUUID,
isEpochTimeInMs: isEpochTimeInMs,
getValInNumber: getValInNumber,
flattenArray: flattenArray,
// getRandomChameleonColorPair: getRandomChameleonColorPair,
removeFromLocalStorage: removeFromLocalStorage,
getFromLocalStorage: getFromLocalStorage,
saveToLocalStorage: saveToLocalStorage,
roundNumberByDecimalPlaces: roundNumberByDecimalPlaces,
getAllQueryStrings: getAllQueryStrings,
convertObjToArray: convertObjToArray,
isObjNotPresentInArr: isObjNotPresentInArr,
isMobileDevice: isMobileDevice,
getRandomFromRange: getRandomFromRange,
recordAudio: recordAudio,
thousandSeparator: thousandSeparator
};
/* ======================================== Var ==================================================== */
/* ======================================== Services =============================================== */
/* ======================================== Public Methods ========================================= */
function removeTimezoneFromDate(dateObj) {
if (getObjType(dateObj) === 'string') {
dateObj = new Date(dateObj);
}
if (getObjType(dateObj) !== 'date' || isNaN(dateObj.getTime())) {
throw "param must be a date object. You passed in: " + dateObj;
}
return new Date(Date.UTC(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate()) - dateObj.getTimezoneOffset())
}
// Code taken directly from: https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript#answer-2901298
function thousandSeparator(number) {
var parts = number.toString().split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return parts.join('.');
}
function recordAudio() {
return new Promise(function(resolved, rejected) {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(function(stream) {
var mediaRecorder = new MediaRecorder(stream);
var audioChunks = [];
mediaRecorder.addEventListener('dataavailable', function(evnt) {
audioChunks.push(evnt.data);
});
var start = function() {
mediaRecorder.start();
};
var stop = function() {
return new Promise(function(resolved, rejected) {
mediaRecorder.onstop = function() {
var newAudioChunks = [];
audioChunks.forEach(function(audioChunk) {
newAudioChunks.push(audioChunk);
});
audioChunks.length = 0;
var audioBlob = new Blob(newAudioChunks);
var audioUrl = URL.createObjectURL(audioBlob);
resolved({
audioRaw: audioChunks,
audioBlob: audioBlob,
audioUrl: audioUrl
});
};
mediaRecorder.stop();
});
};
var play = function(audioUrl) {
(new Audio(audioUrl)).play();
}
resolved({
start: start,
stop: stop,
play: play
});
}, function(err) {
rejected(err);
});
});
}
/**
* Code taken from: https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range#answer-1527834
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomFromRange(minimum, maximum) {
return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
}
function isMobileDevice(type) {
var isAndroid = navigator.userAgent.match(/Android/i);
var isIos = navigator.userAgent.match(/iPhone|iPad|iPod/i);
var isBlackberry = navigator.userAgent.match(/BlackBerry/i);
var isOperaMini = navigator.userAgent.match(/Opera Mini/i);
var isWindows = navigator.userAgent.match(/IEMobile/i);
if(isObjPresent(type)) {
type = type.toLowerCase();
if (type === 'android') {
if (isAndroid) return 'android';
return false;
} else if (type === 'blackberry') {
if (isBlackberry) return 'blackberry';
return false;
} else if (type === 'ios') {
if (isIos) return 'ios';
return false;
} else if (type === 'opera') {
if (isOperaMini) return 'opera';
return false;
} else if (type === 'windows') {
if (isWindows) return 'windows';
return false;
}
} else {
if (isAndroid) {
return 'android';
} else if (isBlackberry) {
return 'blackberry';
} else if (isIos) {
return 'ios';
} else if (isOperaMini) {
return 'opera';
} else if (isWindows) {
return 'windows';
} else {
return false;
}
}
}
function isObjNotPresentInArr(arr1, val, comparisonKey) {
var isNotPresent = true;
for(var i=0, j=arr1.length; i<j; i++) {
if(arr1[i][comparisonKey] === val[comparisonKey]) {
isNotPresent = false;
break;
}
}
return isNotPresent;
}
function convertObjToArray(obj, propNameForKey){
var arr = [];
for(var k in obj) {
if(obj.hasOwnProperty(k)) {
if(getObjType(propNameForKey) === 'string' && isObjPresent(propNameForKey)){
obj[k][propNameForKey] = k;
}
arr.push(obj[k]);
}
}
return arr;
}
function getAllQueryStrings(url) {
var queryStringsAsList = [];
var queryStringAsObj = {};
if(url.split('?')[1]) {
var queryStringKey = '';
var queryStringVal = '';
url.substring(url.indexOf('?') + 1).split('&').forEach(function(currentE) {
queryStringKey = currentE.split('=')[0];
queryStringVal = currentE.split('=')[1];
queryStringsAsList.push({
key: queryStringKey,
val: queryStringVal
});
queryStringAsObj[queryStringKey] = queryStringVal
})
}
return {
urlOriginal: url,
urlWithoutQueryStrings: url.split('?')[0],
queryStringsAsList: queryStringsAsList,
queryStringAsObj: queryStringAsObj
}
}
// Code is from: https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary#answer-12830454
function roundNumberByDecimalPlaces(num, numberOfDecimalPlaces) {
if(!isObjPresent(num) && !isObjPresent(numberOfDecimalPlaces)) {
throw new Error ('roundNumberByDecimalPlaces have 2 params. Either one must be present');
} else {
if(!isObjPresent(num) && isObjPresent(numberOfDecimalPlaces)) {
return 0;
} else if (isObjPresent(num) && !isObjPresent(numberOfDecimalPlaces)) {
return num;
}
}
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + numberOfDecimalPlaces) + "e-" + numberOfDecimalPlaces);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + numberOfDecimalPlaces > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + numberOfDecimalPlaces)) + "e-" + numberOfDecimalPlaces);
}
}
function removeFromLocalStorage(name) {
return localStorage.removeItem(name);
}
function getFromLocalStorage(name) {
return JSON.parse(localStorage.getItem(name));
}
function saveToLocalStorage(name, obj) {
return localStorage.setItem(name, JSON.stringify(obj));
}
function isMobileDevice(type) {
var isAndroid = navigator.userAgent.match(/Android/i);
var isIos = navigator.userAgent.match(/iPhone|iPad|iPod/i);
var isBlackberry = navigator.userAgent.match(/BlackBerry/i);
var isOperaMini = navigator.userAgent.match(/Opera Mini/i);
var isWindows = navigator.userAgent.match(/IEMobile/i);
if(isObjPresent(type)) {
type = type.toLowerCase();
if (type === 'android') {
if (isAndroid) return 'android';
return false;
} else if (type === 'blackberry') {
if (isBlackberry) return 'blackberry';
return false;
} else if (type === 'ios') {
if (isIos) return 'ios';
return false;
} else if (type === 'opera') {
if (isOperaMini) return 'opera';
return false;
} else if (type === 'windows') {
if (isWindows) return 'windows';
return false;
}
} else {
if (isAndroid) {
return 'android';
} else if (isBlackberry) {
return 'blackberry';
} else if (isIos) {
return 'ios';
} else if (isOperaMini) {
return 'opera';
} else if (isWindows) {
return 'windows';
} else {
return false;
}
}
}
/**
* The below is shamelessly taken from 'http://stackoverflow.com/a/27282907'
* - This is done in a linear time O(n) without recursion
* - Memory complexity is O(1) or O(n) if mutable param is set to false
*/
function flattenArray(array, mutable) {
var toString = Object.prototype.toString;
var arrayTypeStr = '[object Array]';
var result = [];
var nodes = (mutable && array) || array.slice();
var node;
if (!array.length) {
return result;
}
node = nodes.pop();
do {
if (toString.call(node) === arrayTypeStr) {
nodes.push.apply(nodes, node);
} else {
result.push(node);
}
} while (nodes.length && (node = nodes.pop()) !== undefined);
result.reverse(); // we reverse result to restore the original order
return result;
}
// function getRandomChameleonColorPair() {
// // This colour pair is taken from => https://camo.githubusercontent.com/747d1a53ed34124c5ab7fb9007f4ccda8da37398/687474703a2f2f692e696d6775722e636f6d2f776b4747576b4e2e706e67
// // From the repo at https://github.com/ViccAlexander/Chameleon
// var colourPair = [
// ['#E74C3C', '#C0392B'], // Flat red
// ['#E67E22', '#D35400'], // Flat orange
// ['#FFCD02', '#FFA800'], // Flat yellow
// ['#f0deb4', '#d5c295'], // Flat sand
// ['#34495e', '#2c3e50'], // Flat navy blue
// ['#2b2b2b', '#262626'], // Flat black
// ['#9b59b6', '#8e44ad'], // Flat magenta
// ['#3a6f81', '#356272'], // Flat teal
// ['#3498db', '#2980b9'], // Flat sky blue
// ['#2ecc71', '#27ae60'], // Flat green
// ['#1abc9c', '#16a085'], // Flat mint
// ['#ecf0f1', '#bdc3c7'], // Flat white
// ['#95a5a6', '#7f8c8d'], // Flat grey
// ['#345f41', '#2d5036'], // Flat forest green
// ['#745ec5', '#5b48a2'], // Flat purple
// ['#5e4534', '#503b2c'], // Flat brown
// ['#5e345e', '#4f2b4f'], // Flat plum
// ['#ef717a', '#d95459'], // Flat watermelon
// ['#a5c63b', '#8eb021'], // Flat lime
// ['#f47cc3', '#d45c9e'], // Flat pink
// ['#79302a', '#662621'], // Flat maroon
// ['#a38671', '#8e725e'], // Flat coffee
// ['#b8c9f1', '#99abd5'], // Flat powder blue
// ['#5065a1', '#394c81'] // Flat blue
// ];
// colourPair = flattenArray(colourPair);
// return colourPair[Math.floor(Math.random() * (colourPair.length - 1))];
// }
// This function will return the following:
// - 111 => return 100
// - 1111 => return 1000
// - 53 => 50
// - 9987 => 9000
// - Less than 10 will return the number itself
function getValInNumber(num) {
if (getObjType(num) == number) {
return num.toString()
.split('')
.map(function(char, index) {
return (index == 0) ? char : '0';
})
.join('') - 0; // -0 Will convert the entire string to a number
} else {
throw new Error(num + ' must be a number!');
}
}
function isEpochTimeInMs(epochDateTime) {
var totalNoOfCharForCurrentTimeInSeconds = Number(Math.floor(Date.now() / 1000)).toString().length;
var totalNoOfCharForCurrentTimeInMilliseconds = Number(Date.now()).toString().length;
if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInMilliseconds) {
return true;
} else if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInSeconds) {
return false;
} else {
throw new TypeError('Parameter passed in is not in seconds or milliseconds');
}
}
/**
* Fast UUID generator, RFC4122 version 4 compliant.
*
* Don't understand how it works? Please visit the link as shown below. Its not meant to be readable as much as its meant to be fast
*
* @author Jeff Ward (jcward.com).
* @license MIT license
* @link http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
**/
function getUUID() {
var lut = [];
for (var i = 0; i < 256; i++) {
lut[i] = (i < 16 ? '0' : '') + (i).toString(16);
}
var d0 = Math.random() * 0xffffffff | 0;
var d1 = Math.random() * 0xffffffff | 0;
var d2 = Math.random() * 0xffffffff | 0;
var d3 = Math.random() * 0xffffffff | 0;
return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
}
function getObjType(object) { // Would really appreciate a unit test to test all for this as manual testing didn't cover everything
var prop = {
'[object Object]': 'object',
'[object Array]': 'array',
'[object String]': 'string',
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object Null]': 'null',
'[object Undefined]': 'undefined',
'[object Function]': 'function',
'[object Date]': 'date',
'[object HTMLDivElement]': 'htmlDivElement',
'[object Blob]': 'blob',
'[object File]': 'file',
'[object MouseEvent]': 'mouse_event',
'[object KeyboardEvent]': 'keyboard_event',
'[object HTMLElement]': 'htmlElement',
'[object Text]': 'objectText',
'[object Map]': 'map'
}
var objType = prop[Object.prototype.toString.call(object)];
if(objType == 'number' && object.toString() == 'NaN') {
return 'NaN';
} else {
return objType;
}
}
/**
* Thie method is inspired by rails .blank? method. This method check for is present (opposite of is blank)
* Rails .blank? method:
* - null.blank? => true
* - false.blank? => true
* - [].blank? => true
* - {}.blank? => true
* - ''.blank? => true
* - 5.blank? => false
* - 0.blank? => false
* Added another check is to check for function.
* An empty function is:
* - function () { }
* - function(param1, param2, param3) { }
* A non empty function is:
* - function() { console.log(); }
* An invalid date will return false for this function
* A valid date will return true for this function
* This will just check if its empty or not and not check if its syntatically correct or not
* @param {object} obj [Since everything in javascript is considered an object, just pass in anything]
* @return {Boolean} [If its not blank, then will return true. Else, it will return false]
*/
function isObjPresent(obj) {
var type = getObjType(obj);
if (type === 'object') {
// This will traverse the entire object keys & check the values.
// If even one of the values isPresent (the type & value is defined in this function itself)
// then it will assume the obj IS present
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if(isObjPresent(obj[key]) === true) {
return true;
}
}
}
return false;
} else if (type === 'array') {
if (obj.length > 0) {
return true;
} else if (obj.length == 0) {
return false;
} else {
throw new Error(obj + ' comes to array if-else but the length is neither 0 or more than 0');
}
} else if (type === 'string') {
if (obj.length > 0) {
return true;
} else if (obj.length == 0) {
return false
} else {
throw new Error(obj + ' comes to string if-else but the length its not 0 or more than 0');
}
} else if (type === 'boolean') {
if (obj === true) {
return true
} else if (obj === false) {
return false;
} else {
throw new Error(obj + ' comes to boolean if-else but is neither true or false');
}
} else if (type === 'number') {
return true; // We assume if the obj passed in is a number, that means it has a value and thus present (either negative or positive value)
} else if (type === 'null') {
return false;
} else if (type === 'undefined') {
return false;
} else if (type === 'function') {
var tmpStr = obj.toString();
var tmpStr2 = tmpStr.substring(tmpStr.indexOf('{') + 1, tmpStr.indexOf('}')).trim().replace(/\r?\n|\r/g, ""); // The RegEx here is to check for: arriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS)
if (isObjPresent(tmpStr2)) {
return true;
} else {
return false;
}
} else if (type === 'date') {
if (isNaN(obj.getTime())) {
return false; // Date is invalid
} else {
return true; // Date is valid
}
} else if (type === 'htmlDivElement' || type === 'htmlElement') {
if(type.toString().length > 0) {
return true;
} else {
return false;
}
} else if (type === 'blob') {
if(obj.size > 0) {
return true;
} else {
return false;
}
} else if (type === 'file') {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return true;
}
}
return false;
} else if (type === 'mouse_event') {
return true;
} else if (type === 'keyboard_event') {
return true;
} else if (type === 'NaN') {
return false;
} else if (type === 'objectText') {
return true;
} else if (type === 'map') {
return true;
} else {
throw new Error(obj + ' is not an array, string, boolean or number. This fn only work with those for now');
}
}
// function getDayInEpoch(validJsDate) {
// if(!isObjPresent(validJsDate)) {
// validJsDate = Date.now();
// }
// var d = new Date(validJsDate);
// if(d === 'Invalid Date') {
// return d;
// }
// return (new Date(d.getFullYear(), d.getMonth(), d.getDate())).getTime();
// }
// function getMonthNameFromEpochDate(dateTimeInEpoch) {
// try {
// var month = new Date(Number(dateTimeInEpoch)).getMonth();
// getMonthNameFromDateObj(month);
// } catch (e) {
// throw new Error('date time is not in number');
// }
// }
// function getDateInDDMMMMYYYY(dateTimeInEpoch) { // Will return dd MMMM YYYY : 01 Jan 2012
// try {
// var dateTimeInNumber = Number(dateTimeInEpoch);
// var month = new Date(Number(dateTimeInEpoch)).getMonth();
// var monthInString = getMonthNameFromDateObj(month);
// return new Date(Number(dateTimeInEpoch)).getDate() + ' ' + monthInString + ' ' + new Date(Number(dateTimeInEpoch)).getFullYear();
// } catch (e) {
// throw new Error('date time is not in number');
// }
// }
function getMonthNameFromDateObj(number, isShortName) {
if(number >= 0 && number <= 11) {
var monthNames = [{
name: 'january',
shortName: 'jan'
}, {
name: 'february',
shortName: 'feb'
}, {
name: 'march',
shortName: 'mac'
}, {
name: 'april',
shortName: 'apr'
}, {
name: 'may',
shortName: 'may'
}, {
name: 'june',
shortName: 'jun'
}, {
name: 'july',
shortName: 'jul'
}, {
name: 'august',
shortName: 'aug'
}, {
name: 'september',
shortName: 'sept'
}, {
name: 'october',
shortName: 'oct'
}, {
name: 'november',
shortName: 'nov'
}, {
name: 'december',
shortName: 'dec'
}];
if(isShortName) {
return monthNames[number].shortName;
} else {
return monthNames[number].name;
}
}
}
function init() {
}
/* ======================================== Private Methods ======================================== */
})();