-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEightyApp.js
More file actions
1890 lines (1731 loc) · 61.8 KB
/
Copy pathEightyApp.js
File metadata and controls
1890 lines (1731 loc) · 61.8 KB
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
/****************************
STANDARDS FOR ADDING NEW FUNCTIONS
1. Consult with the Data Quality Manager before beginning modification of base 80app.
2. Write tests. Tests should cover handling all bad input (undefined/null/""), handling an expected pattern of input, and predictable edge cases.
Help for writing tests can be found in the 'test' directory
3. Consult with a member of the Ops team after method and test completion. They will approve/deny pushing your changes to live.
STANDARDS FOR WRITING NEW FUNCTIONS
1. Functions should have simple, meaningful names. Preferably without abbreviations.
2. Functions should not be domain specific. Functions should be applicable to common concepts, not one specific website.
3. Make sure your code is legible and consistently formatted. It is preferred to have code with better readability than fast, but illegible, code.
4. When false input is received (undefined/null/"") functions should usually return null, except for functions that explicitly return text.
Functions that return text should instead return an empty string upon receiving bad input.
****************************/
const builderApps = require('./builderApps');
const _ = require('lodash');
var EightyAppBase = function() {
var authStatus;
var initialize = function() {
authStatus = false;
};
/*
* Outputs a String to the 80appTester's console box
* @param {String} msg The string to output
*/
this.say = function(msg) {
process.send({
message: msg.toString()
});
};
this.version = '3.0';
// Add all 80appBuilder apps to the base 80app
// These should only be used from within the 80appBuilder on the
// new version of the 80legs Portal
Object.keys(builderApps).forEach(app => {
this[app] = builderApps[app];
});
/**
* Default function Crawl Health Monitor will use to determine health of 80app execution.
* @param {Object} crawlJob
* @param {Object} crawlResult
* @param {String} url
* @param {Object} extras
*/
this.checkHealth = function(crawlJob, crawlResult, url, extras) {
// Handle 80app function executions (parseLinks/processDocument) only once per crawlJob
let pageTypes = {
processDocument: true,
parseLinks: true
};
if (crawlResult.processDocument.error) {
pageTypes.processDocument = false;
}
if (crawlResult.parseLinks.error) {
pageTypes.parseLinks = false;
}
const dataType = extras.dataType;
// If both dataType and crawl result(s) are available scan through them and test for target fields
if (crawlResult.processDocument.result && crawlResult.processDocument.result.data && dataType) {
// Standardize data to array of result(s)
let results = crawlResult.processDocument.result.data;
results = Array.isArray(results) ? results : [results];
// Check for target fields based on dataType.
for (let data of results) {
switch (dataType) {
case 'business':
if (data.latitude && data.longitude) {
if (pageTypes.latlong) {
pageTypes.latlong.push(true);
} else {
pageTypes.latlong = [true];
}
}
break;
case 'product':
if (data.upc) {
if (pageTypes.upc) {
pageTypes.upc.push(true);
} else {
pageTypes.upc = [true];
}
}
break;
case 'property':
if (data.mostRecentStatus && data.mostRecentStatus.length) {
if (pageTypes.mostRecentStatus) {
pageTypes.mostRecentStatus.push(true);
} else {
pageTypes.mostRecentStatus = [true];
}
}
}
}
}
return { pageTypes };
}
/**
* Converts 24 hour time to the corresponding 12 hour time string
* @param {String} time24
*/
this.convert24HourTime = function(time24){
if (!time24) {
return '';
}
let splitTime = time24.split(':');
let hours = splitTime[0].replace(/[^\d]/g, '') || '';
let minutes = splitTime[1] && splitTime[1].replace(/[^\d]/g, '');
minutes = minutes ? ':' + minutes : '';
let meridiem = '';
if (!hours || hours > 24 || hours < 0) {
// Invalid hours
return '';
}
if (hours >= 12) {
hours %= 12;
meridiem = ' PM';
} else {
meridiem = ' AM';
}
if (hours == 0) {
hours = 12;
meridiem = ' AM';
}
return hours + minutes + meridiem;
};
/**
* Returns the corresponding number expression (as a string) for the attribute passed in. Number expressions
* may conditionally have decimals, or dashes to delineate ranges or negative numbers. '1-2', '.4-0.54', and '-.6'
* are all valid number expressions
* getNumberValue('I have 2 dogs and 3 cats', /dogs/) => 2
* getNumberValue('I have 2 dogs and 3 cats', /cats/) => 3
* see test.js for more examples
* @param {String} str the String to parse for numbers
* @param {RegExp} attribute the pattern to match within the string
*/
this.getNumberValue = function(str, attribute) {
if (!str) {
// Only want to work with valid strings
return '';
}
if (!(attribute instanceof RegExp)) {
// Want attribute to be a regexp only
throw new TypeError('invalid regular expression ' + attribute.toString());
}
// Really scary regex that matches the closest number expression before and the closest number expression after the first occurance of attribute
let regex = new RegExp('(\\d*\\.??\\d*-??\\d*\\.??\\d+)?[^\\d]*?' + attribute.source + '[^\\d]*(\\d*\\.??\\d*-??\\d*\\.??\\d+)?', 'g' + attribute.flags);
// So that we can properly collect numbers with commas
str = str.replace(/(\d),(\d)/g, ($0, $1, $2) => { return $1 + $2; });
let match = regex.exec(str);
if (!match || !match[1] && !match[2]) {
// If attribute pattern wasn't matched in str
return '';
}
if (!match[1]) {
// If only number expression after attribute was found
return match[2];
}
if (!match[2]) {
// If only number expression before attribute was found
return match[1];
}
// Return the number expression match that was closest to the attribute match
let matchInfo = str.match(attribute);
let matchLength = matchInfo[0].length;
let matchStartIndex = matchInfo.index;
let matchEndIndex = matchStartIndex + matchLength;
// Distance from first match to attribute match
let distOne = Math.abs(matchStartIndex - (str.match(match[1]).index + match[1].length));
// Distance from the second match to attribute match
let distTwo = Math.abs((regex.lastIndex - match[2].length) - matchEndIndex);
let matches = {
[distOne] : match[1],
[distTwo] : match[2]
};
return matches[Math.min(distOne, distTwo)];
};
/**
* Removes all duplicates from each array field in data object. Duplicates are defined by
* @param comparator. If no comparator function is specified, defaults to _.isEqual() with
* case insensitive string comparisons
* @param {Object} data
* @param {function} comparator a function to determine object equality.
* @return {Object} data object where all duplicates from each array field are removed. Returns null if @param data
* is fase, not an object, or an array instance
*/
this.removeAllDuplicates = function(data, comparator) {
if (!data || typeof(data) !== 'object' || data instanceof Array) {
// Only want to work with objects, not arrays
return null;
}
let app = this;
// Function for string comparison
let stringComparator = function(obj1, obj2) {
// If obj1 and obj2 are both strings, remove extra white space and perform case insensitive comparison
if (typeof(obj1) === 'string' && typeof(obj2) === 'string') {
return app.removeExtraWhitespace(obj1).toLowerCase() === app.removeExtraWhitespace(obj2).toLowerCase();
}
};
if (!comparator) {
// If comparator not defined, set default comparator to be used for deep comparison of objects
comparator = (obj1, obj2) => { return _.isEqualWith(obj1, obj2, stringComparator); };
}
for (let attr in data) {
let field = data[attr];
if (field instanceof Array) {
// If the field is an array, reassing it to an array where duplicates are removed
data[attr] = _.uniqWith(field, comparator);
}
}
return data;
};
/**
* For each value in an array, removes any trailing whitespace
* @param {Array} array array of strings to trim
* @return {Array} retruns the input array with each item being trimed
*/
this.trimAll = function(array) {
if (array !== null && array instanceof Array && array.length > 0)
for (var i = 0; i < array.length; i++) {
if (typeof array[i] === 'string' || array[i] instanceof String) {
var tmp = this.removeExtraWhitespace(array[i]);
if (tmp.length>0)
array[i] = tmp;
} else
return null;
}
else
return null;
return array;
};
this.processDocument = function(html, url, headers, status, jQuery) {};
this.parseLinks = function(html, url, headers, status, jQuery) {};
this.parseJSON = function(text) {
return JSON.parse(text);
};
this.parseHtml = function(text, $) {
text = text.replace(/(<img)\+*?/g, '<img80');
return $(text);
};
this.parseXml = function(text, $) {
text = text.replace(/(<img)\+*?/g, '<img80');
return $(text);
};
this.extractHostname = function(url) {
var hostname;
//find & remove protocol (http, ftp, etc.) and get hostname
if (url.indexOf('://') > -1) {
hostname = url.split('/')[2];
}
else {
hostname = url.split('/')[0];
}
//find & remove port number
hostname = hostname.split(':')[0];
//find & remove "?"
hostname = hostname.split('?')[0];
return hostname;
};
this.extractRootDomain = function(url) {
var domain = this.extractHostname(url),
splitArr = domain.split('.'),
arrLen = splitArr.length;
//extracting the root domain here
//if there is a subdomain
if (arrLen > 2) {
domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
//check to see if it's using a Country Code Top Level Domain (ccTLD) (i.e. ".me.uk")
if (splitArr[arrLen - 2].length == 2 && splitArr[arrLen - 1].length == 2) {
//this is using a ccTLD
domain = splitArr[arrLen - 3] + '.' + domain;
}
}
return domain;
};
/**
* Removes any special characters from a string
* @param {String} text the string to remove special characters from
* @return {String} the input string with any special characters removed
*/
this.getPlainText = function(text) {
if (!text) {
return '';
}
text = text
.replace(/[^a-z0-9\s.'-:!]/gi, '') // remove all characters not a-z, 0-9, and certain punctuation, ignoring case
.replace(/\s{2,}/g, ' ') // replace any two whitespace characters next to each other with a single space
.replace(/\s/g, ' '); // replace all whitespace characters (\t,\n,\r, ) with space
// trim
return text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
/**
* Removes any trailing whitespace characters and any instance of \t, \n, \r, \v, or \f
* @param {String} text the string from which to remove extra whitespace
* @return {String} the input string with excess whitespace removed
*/
this.removeExtraWhitespace = function(text) {
if (!text) {
return '';
}
else {
return text.replace(/\s{2,}/g, ' ').replace(/\s/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
};
/**
* Returns whether @param obj is truthy and should be returned by an extraction function
* @param {*} obj
* @return {boolean} whether it is safe to operate on @param obj and whether it should be returned
* at the end of an extraction function. Must be truthy, strings must have one non-whitespace character,
* arrays and DOM objects must have length > 0, and generic objects must have at least one non-prototype
* property
*/
this.isValid = function(obj) {
if (!obj && obj !== 0) {
// Ensure obj is truthy (zero is the exception as it is falsey and a valid number)
return false;
}
if (obj instanceof String || typeof(obj) === 'string') {
// Ensure strings have at least one non-whitespace character
return /[^\s]/.test(obj);
}
if (obj.hasOwnProperty('length')) {
// Ensures that arrays and DOM objects aren't empty
return obj.length > 0;
}
if (obj instanceof Date) {
// Ensures that all dates are valid
return obj.toString() !== 'Invalid Date';
}
if (obj instanceof Object ) {
// Ensures that obj isn't an empty object
return Object.keys(obj).length > 0;
}
if (typeof(obj) === 'number' && obj < 0) {
return false;
}
return true;
};
/**
* 'Deep' trims every instance of string in an object or array, or just the object itself if it is a string
* @param {*} object element to be deep trimmed
* @return {*} element of same type as @param object, with all instances of string trimmed
*/
this.trimObject = function(object) {
let app = this;
if (typeof object === 'string') {
// Trim the string
object = app.removeExtraWhitespace(object);
} else if (object instanceof Array) {
// Trim all strings in the array
object = object.map(function (e) {
return app.trimObject(e);
});
} else if (object instanceof Object) {
// Trim every value in the object
var keys = Object.keys(object);
for (var k in keys) {
var key = keys[k];
var temp = object[key];
object[key] = app.trimObject(temp);
}
}
return object;
};
// decode unicode by inputting a selective regex and a string
// make sure to use a global regex to replace all instances of unicode in the input string
// code adapted from: http://stackoverflow.com/questions/7885096/how-do-i-decode-a-string-with-escaped-unicode
this.decodeUnicode = function(regex, str) {
if (str !== undefined) {
var decodedString = str.replace(regex, function(match, grp) {
return String.fromCharCode(parseInt(grp, 16));
});
return decodedString;
}
};
/**
* Given an object capable of generating a Date object, formats it into the format
* yyyy-MM-ddTHH:mm:ssZ
* @param {Object} date an object used to construct a Date object
* @return {String} a date String formatted yyyy-MM-ddTHH:mm:ssZ
*/
this.formatDate = function(date) {
// yyyy-MM-ddTHH:mm:ssZ
date = new Date(date);
return date.getUTCFullYear() + '-' +
(date.getUTCMonth() + 1 < 10 ? '0' + (date.getUTCMonth() + 1) : '' + (date.getUTCMonth() + 1)) + '-' +
(date.getUTCDate() < 10 ? '0' + date.getUTCDate() : '' + date.getUTCDate()) +
'T' +
(date.getUTCHours() < 10 ? '0' + date.getUTCHours() : '' + date.getUTCHours()) + ':' +
(date.getUTCMinutes() < 10 ? '0' + date.getUTCMinutes() : '' + date.getUTCMinutes()) + ':' +
(date.getUTCSeconds() < 10 ? '0' + date.getUTCSeconds() : '' + date.getUTCSeconds()) +
'Z';
};
/**
* Removs HTML tags from a string
* @param {String} text the text to process
* @param {String} input string with any HTML tags removed
*/
this.removeTag = function(text) {
if (!text){
return '';
}//if: input is false, return empty string
return text.replace(/<.*?>/g, '');
};
/**
* Gets the first match from a group of regex matches
* @param {String} text String to execute regex on
* @param {RegExp} regexp RegExp object to run text against
* @return {String} first match
*/
this.getFirstMatch = function(text, regexp) {
var matchedGroup = regexp.exec(text);
if (matchedGroup !== null && matchedGroup !== undefined) {
return matchedGroup[1].trim();
}
};
/**
* Appends an EightyFlag value to a link
* @param {String} eightyValue the EightyFlag to add
* @param {String} link the link upon which to append eightyValue
* @return {String} the link with the EightyFlag
*/
this.append80FlagToLink = function(eightyValue, link) {
if (!eightyValue && !link){
return null;
}
else if (!eightyValue){
return link;
}
else if (!link){
return eightyValue;
}
// Encode 80value to handle 80values with uri forbidden characters
eightyValue = encodeURIComponent(eightyValue);
var returnLink = link;
if (link.indexOf('?') >= 0 && !/[?&]$/.test(link)) {
returnLink = link + '&80flag=' + eightyValue;
}
else if (/[?&]$/.test(link)) {
returnLink = link + '80flag=' + eightyValue;
}
else {
returnLink = link + '?80flag=' + eightyValue;
}
return returnLink;
};
/**
* Extracts the value of an EightyFlag from a link
* @param {String} link a link with an EightyFlag
* @return {String} the value contained in the EightyFlag on the link
*/
this.get80Value = function(link) {
if (link) {
var eightyFlagIndex = link.indexOf('80flag=');
if (eightyFlagIndex === -1){
return null;
}//if: no index of 80flag=
var trimmedURL = link.substring(eightyFlagIndex);
var endIndex = trimmedURL.indexOf('&');
if (endIndex === -1){
endIndex = link.length;
}//if: endIndex was not found on an ampersand
var eightyValue = trimmedURL.substring('80flag='.length, endIndex);
// Decode 80value so that the return value matches parameter passed to append80FlagToLink()
eightyValue = decodeURIComponent(eightyValue);
return eightyValue;
}
return null;
};
// IMPORTANT Usage Note: Use makeLink on a url BEFORE appending an 80flag for review URLs. Otherwise
// it will match on the sourceURL rather than the actual url
this.makeLink = function(domain, href) {
if (!domain && !href) {
return null;
}
else if (!domain) {
return href;
}
else if (!href) {
return domain;
}
if (domain.indexOf('http://') == -1 && domain.indexOf('https://') == -1) {
domain = 'http://' + domain;
}
var prefix;
prefix = domain.indexOf('https://') !== -1 ? 'https' : 'http';
var base = prefix == 'https' ? domain.slice(8) : domain.slice(7);
if (base.indexOf('/') !== -1) {
domain = prefix + '://' + base.slice(0, base.indexOf('/'));
} else if (base.indexOf('?') !== -1) {
domain = prefix + '://' + base.slice(0, base.indexOf('?'));
}
if (href.indexOf('http://') !== -1 || href.indexOf('https://') !== -1) {
return href;
}
var domainCheck = prefix == 'https' ? domain.slice(8) : domain.slice(7);
domainCheck = domainCheck.indexOf('www.') !== -1 ? domainCheck.slice(4) : domainCheck;
if (href.indexOf(domainCheck) !== -1) {
if (href.indexOf('http://') == -1 && href.indexOf('https://') == -1) {
if (href.indexOf('/') == 0){
if (href.indexOf('//') == 0){
return 'http:' + href;
}
return 'http:/' + href;
}
return 'http://' + href;
} else {
return href;
}
} else {
//outside domains are tagged with a double-slash in most cases
if (href.indexOf('//') === 0){
//must add http: - href would have been returned earlier if it had it
return 'http:' + href;
}
else if (domain[domain.length - 1] == '/' && href[0] == '/') {
domain = domain.slice(0, -1);
} else if (domain[domain.length - 1] !== '/' && href[0] !== '/') {
domain += '/';
}
return domain + href;
}
};
/**
* Converts an alphanumeric phone number to a purely numeric one
* May be used before or after removing special characters
* @param {String} alphanumericPhone an alphanumeric phone number
* @return {String} the alphanumeric phone number converted to numeric form
*/
this.convertAlphanumericPhone = function(rawPhone) {
// If there are no alphabetic characters in the phone, don't change it
if (!/\D/.test(rawPhone))
return rawPhone;
// There must be no alphabetic characters in the phone, convert them
var convertedPhone = rawPhone.toUpperCase().split('');
for (var i = 0; i < convertedPhone.length; i++)
switch (convertedPhone[i]) {
case 'A':
case 'B':
case 'C':
convertedPhone.splice(i, 1, '2');
break;
case 'D':
case 'E':
case 'F':
convertedPhone.splice(i, 1, '3');
break;
case 'G':
case 'H':
case 'I':
convertedPhone.splice(i, 1, '4');
break;
case 'J':
case 'K':
case 'L':
convertedPhone.splice(i, 1, '5');
break;
case 'M':
case 'N':
case 'O':
convertedPhone.splice(i, 1, '6');
break;
case 'P':
case 'Q':
case 'R':
case 'S':
convertedPhone.splice(i, 1, '7');
break;
case 'T':
case 'U':
case 'V':
convertedPhone.splice(i, 1, '8');
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
convertedPhone.splice(i, 1, '9');
break;
}
return convertedPhone.join('');
};
/**
* Removes all duplicates from an array, where equality is determined by ==
* IMPORTANT NOTE: all instances of Object are considered equal by this method, only use on primitives
* @param arr an array containing elements of any type
* @returns a new array where all duplicate primitives and all objects but one have been removed. Returns
* null if @param arr is falsey
*/
// eliminateDuplicates code borrowed from: http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
this.eliminateDuplicates = function(arr) {
if (!arr){
return null;
}//if: arr is falsey
var i;
var len = arr.length;
var out = [];
var obj = {};
for (i = 0; i < len; i++) {
if (!obj[arr[i]] && arr[i].toString().length>0) {
obj[arr[i]] = {};
out.push(arr[i]);
}
}
return out;
};
//$= under $25
//$$= $25-$40
//$$$= $50-$55
//$$$$= above $55
//£ = under £15
//££ = £15-£25
//£££ = £30-£35
//££££ = above £35
//replaces dollar sign notation into dollar amounts to capture price range details
this.getPriceRangeReplace = function(text, currency) {
if (!text || !currency){
return {};
}
var priceRangeObj = {};
if (currency === 'USD') {
priceRangeObj.priceRangeCurrency = 'USD';
if (text === '$$$$') {
priceRangeObj.priceRangeMin = 55;
} else if (text === '$$$') {
priceRangeObj.priceRangeMin = 40;
priceRangeObj.priceRangeMax = 55;
} else if (text === '$$') {
priceRangeObj.priceRangeMin = 25;
priceRangeObj.priceRangeMax = 40;
} else if (text === '$') {
priceRangeObj.priceRangeMin = 0;
priceRangeObj.priceRangeMax = 25;
}
} else if (currency === 'GBP') {
priceRangeObj.priceRangeCurrency = 'GBP';
if (text === '££££') {
priceRangeObj.priceRangeMin = 35;
} else if (text === '£££') {
priceRangeObj.priceRangeMin = 25;
priceRangeObj.priceRangeMax = 35;
} else if (text === '££') {
priceRangeObj.priceRangeMin = 15;
priceRangeObj.priceRangeMax = 25;
} else if (text === '£') {
priceRangeObj.priceRangeMin = 0;
priceRangeObj.priceRangeMax = 15;
}
} else if (currency === 'YEN') {
priceRangeObj.priceRangeCurrency = 'YEN';
if (text === '¥¥¥¥') {
priceRangeObj.priceRangeMin = 6175;
} else if (text === '¥¥¥') {
priceRangeObj.priceRangeMin = 4491;
priceRangeObj.priceRangeMax = 6175;
} else if (text === '¥¥') {
priceRangeObj.priceRangeMin = 2807;
priceRangeObj.priceRangeMax = 4491;
} else if (text === '¥') {
priceRangeObj.priceRangeMin = 0;
priceRangeObj.priceRangeMax = 2807;
}
} else if (currency === 'EUR') {
priceRangeObj.priceRangeCurrency = 'EUR';
if (text === '€€€€') {
priceRangeObj.priceRangeMin = 47;
} else if (text === '€€€') {
priceRangeObj.priceRangeMin = 34;
priceRangeObj.priceRangeMax = 47;
} else if (text === '€€') {
priceRangeObj.priceRangeMin = 21;
priceRangeObj.priceRangeMax = 34;
} else if (text === '€') {
priceRangeObj.priceRangeMin = 0;
priceRangeObj.priceRangeMax = 21;
}
}
return priceRangeObj;
};
// converts a price string into ####.##
this.normalizePrice = function(numberString) {
if (!numberString){
return null;
}//if: input numberString is falsey
numberString = numberString.trim();
var numberStringLength = numberString.length;
//Check if it is using the comma as a decimal separator and change it to the dot separator
if (numberString.substr(numberString.length-3, 3).match(/,/)){
var last3OriginalChars = numberString.substr(numberString.length-3, 3);
var last3NewChars = numberString.substr(numberString.length-3, 3).replace(/,/,'.');
var re = new RegExp(last3OriginalChars+'$');
numberString = numberString.replace(re, last3NewChars);
}
var numberMatch = numberString.match(/(\d+(?:[,|.]\d+)*)+/);
if (!numberMatch)
return null;
if (numberMatch.length>=2){
var number = parseFloat(numberMatch[1].replace(/,/g,''));
if (!isNaN(number)) {
number = number.toFixed(2);
return numberString.replace(/(\d+(?:,|.\d+)*)+/, number);
}
}
return null;
};//function: normalizePrice
/**
* Converts special characters into ASCII
* @param {String} string the string to convert to ASCII
* @return {String} string converted to ASCII
*/
this.replaceSpecialCharacters = function(string) {
var stringWithSpecialCharacters = string;
var translate = {
'Ä': 'A',
'ä': 'a',
'Ç': 'C',
'ç': 'c',
'Ğ': 'G',
'ğ': 'g',
'İ': 'I',
'ı': 'i',
'Ö': 'O',
'ö': 'o',
'Ş': 'S',
'ş': 's',
'Ü': 'U',
'ü': 'u',
'ß': 'ss',
'à': 'a',
'á': 'a',
'â': 'a',
'ã': 'a',
'è': 'e',
'é': 'e',
'ê': 'e',
'ë': 'e',
'ě': 'e',
'œ': 'oe',
'ì': 'i',
'í': 'i',
'î': 'i',
'ï': 'i',
'ñ': 'n',
'ò': 'o',
'ó': 'o',
'ô': 'o',
'õ': 'o',
'ř': 'r',
'ù': 'u',
'ú': 'u',
'û': 'u',
'ý': 'y',
'ÿ': 'y',
'ž': 'z',
'À': 'A',
'Á': 'A',
'Â': 'A',
'Ã': 'A',
'È': 'E',
'É': 'E',
'Ê': 'E',
'Ë': 'E',
'Ì': 'I',
'Í': 'I',
'Î': 'I',
'Ï': 'I',
'Ñ': 'N',
'Ò': 'O',
'Ó': 'O',
'Ô': 'O',
'Õ': 'O',
'Ù': 'U',
'Ú': 'U',
'Û': 'U',
'Ý': 'Y',
'Ž': 'Z'
};
var replacementRegEx = new RegExp(Object.keys(translate).join('|'), 'g');
var replacedString = stringWithSpecialCharacters.replace(replacementRegEx, function(letter) {
return translate[letter];
});
return replacedString;
};
// Maps all American states and Canadian provinces to two letter abbreviation
// Obselete now that addressParser is active
this.stateCodeConverter = {
'Alabama': 'AL',
'Alaska': 'AK',
'American Samoa': 'AS',
'Arizona': 'AZ',
'Arkansas': 'AR',
'California': 'CA',
'Colorado': 'CO',
'Connecticut': 'CT',
'Delaware': 'DE',
'District Of Columbia': 'DC',
'Federated States Of Micronesia': 'FM',
'Florida': 'FL',
'Georgia': 'GA',
'Guam': 'GU',
'Hawaii': 'HI',
'Idaho': 'ID',
'Illinois': 'IL',
'Indiana': 'IN',
'Iowa': 'IA',
'Kansas': 'KS',
'Kentucky': 'KY',
'Louisiana': 'LA',
'Maine': 'ME',
'Marshall Islands': 'MH',
'Maryland': 'MD',
'Massachusetts': 'MA',
'Michigan': 'MI',
'Minnesota': 'MN',
'Mississippi': 'MS',
'Missouri': 'MO',
'Montana': 'MT',
'Nebraska': 'NE',
'Nevada': 'NV',
'New Hampshire': 'NH',
'New Jersey': 'NJ',
'New Mexico': 'NM',
'New York': 'NY',
'North Carolina': 'NC',
'North Dakota': 'ND',
'Northern Mariana Islands': 'MP',
'Ohio': 'OH',
'Oklahoma': 'OK',
'Oregon': 'OR',
'Palau': 'PW',
'Pennsylvania': 'PA',
'Puerto Rico': 'PR',
'Rhode Island': 'RI',
'South Carolina': 'SC',
'South Dakota': 'SD',
'Tennessee': 'TN',
'Texas': 'TX',
'Utah': 'UT',
'Vermont': 'VT',
'Virgin Islands': 'VI',
'Virginia': 'VA',
'Washington': 'WA',
'West Virginia': 'WV',
'Wisconsin': 'WI',
'Wyoming': 'WY',
'Slberta': 'AB',
'British Columbia': 'BC',
'Manitoba': 'MB',
'New Brunswick': 'NB',
'Newfoundland Snd Labrador': 'NL',
'Nova Scotia': 'NS',
'Nunavut': 'NU',
'Ontario': 'ON',
'Prince Edward Island': 'PE',
'Quebec': 'QC',
'Saskatchewan': 'SK',
'Yukon': 'YT'
};
// Maps countries to two letter abbreviations
// Obselete now that addressParser is active
this.countryCodeConverter = {
'Albania': 'AL',
'Afghanistan': 'AF',
'Andorra': 'AD',
'Anguilla': 'AI',
'Algeria': 'DZ',
'American Samoa': 'AS',
'Angola': 'AO',
'Antigua and Barbuda': 'AG',
'Antigua & Barbuda': 'AG',
'Antigua': 'AG',
'Argentina': 'AR',
'Armenia': 'AM',
'Aruba': 'AW',
'Australia': 'AU',
'Austria': 'AT',
'Azerbaijan': 'AZ',
'Bahamas': 'BS',
'Bahrain': 'BH',
'Bangladesh': 'BD',
'Barbados': 'BB',
'Bay Islands Honduras': 'HN',
'Belarus': 'BY',
'Belize': 'BZ',
'Belgium': 'BE',
'Benin': 'BJ',
'Bermuda': 'BM',
'Bhutan': 'BT',
'Bosnia and Herzegovina': 'BA',
'Bolivia': 'BO',
'Bonaire': 'BQ',
'Botswana': 'BW',
'Bouvet Island': 'BV',
'Brazil': 'BR',
'British Virgin Islands': 'VG',
'UK Virgin Islands': 'VG',
'British Indian Ocean Territory': 'IO',
'Brunei Darussalam': 'BN',
'Brunei': 'BN',