-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjavascriptCodeSamples.js
459 lines (408 loc) · 15.3 KB
/
javascriptCodeSamples.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
/*jslint browser: true, devel: true, debug: true */
"use strict";
/**
* Add helper methods
*/
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
if (typeof Object.create !== "function") {
Object.create = function (o) {
var F = function () {
};
F.prototype = o;
return new F();
};
}
Object.method("superior", function (name) {
var that = this,
method = that[name];
return function () {
return method.apply(that, arguments);
};
});
/**
* Example: Using the functional inheritance pattern to gain privacy and super functionality
*/
var functionalPeople = {
/**
* Creates a casual person Object
*
* @param {Object} spec The spec containing the values to use
*
* @return {Object}
*/
casualPerson: function (spec) {
spec.male = (spec.male === undefined) ? true : !!spec.male;
var that = {};
that.getName = function () {
return spec.firstName || "";
};
that.getEmail = function () {
return spec.email || "";
};
that.isMale = function () {
return spec.male;
};
that.toString = function () {
return "\n\t" + that.getName() + "\n\t" + that.getEmail();
};
return that;
},
/**
* Creates a professional person Object
*
* @param {Object} spec The spec containing the values to use
*
* @return {Object}
*/
professionalPerson: function (spec) {
var that = this.casualPerson(spec),
superGetName = that.superior("getName");
that.getName = function () {
return that.getTitle() + superGetName() + " " + spec.lastName;
};
that.getTitle = function () {
return that.isMale() ? "Mr. " : "Miss. ";
};
that.getCompany = function () {
return spec.company || "";
};
that.toString = function () {
return "\n\t" + that.getName() + "\n\t" + that.getEmail() + "\n\t" + that.getCompany();
};
return that;
}
};
(function () {
var someGuy = functionalPeople.casualPerson({
firstName: "Derek",
email: "derek@derekdonnelly.com"
}),
someProfessional = functionalPeople.professionalPerson({
firstName: "Derek",
lastName: "Donnelly",
email: "derek@codex9.com",
company: "Codex9 Ltd.",
male: true
});
console.log("\nsomeGuy: " + someGuy.toString());
console.log("\nsomeProfessional: " + someProfessional.toString());
}());
/**
* Example: Some custom Number utility methods added to the Number prototype
*/
(function () {
var inputNumber, constrainedNumber, randomBoolean;
/**
* Constrains a Number to within a range
*
* var inputNumber = 13;
* var constrainedNumber = inputNumber.constrainToRange(0, 6);
*
* @param {Number} min The minimum range Number
* @param {Number} max The maximum range Number
*
* @return {Number} The constrained Number
*/
Number.method("constrainToRange", function () {
return function constrainToRange(min, max) {
try {
if (typeof min !== "number" || typeof max !== "number") {
throw new TypeError("constrainToRange(...) requires Number args");
}
if (this >= min) {
return (this <= max) ? this.valueOf() : max;
}
return min;
} catch (e) {
console.log(e.name + ": " + e.message);
throw e; // rethrow to inform unit tests
}
};
}());
inputNumber = 13;
constrainedNumber = inputNumber.constrainToRange(0, 6);
console.log("\ninputNumber: " + inputNumber + ", inputNumber.constrainedNumber(0, 6): " + constrainedNumber);
console.log("typeof constrainedNumber: " + typeof constrainedNumber);
Number.method("integer", function () {
return Math[this < 0 ? "ceil" : "floor"](this);
});
console.log("\n(-9 / 2).integer(): " + (-9 / 2).integer());
/**
* Returns a random Number within a range
*
* var randomNumber = Number().randomWithinRange(0, 10);
* var randomBoolean = !!Number().randomWithinRange(0, 1);
*
* @param {Number} min The minimum range Number
* @param {Number} max The maximum range Number
* @param {Boolean} [round=true] Round the return value.
*
* @return {Number} The random Number
*/
Number.method("randomWithinRange", function () {
return function randomWithinRange(min, max, round) {
try {
if (typeof min !== "number" || typeof max !== "number") {
throw new TypeError("randomWithinRange(...) requires Number args");
}
if (max < min) {
throw new RangeError("randomWithinRange(...) max should not be less than min");
}
if (max === min) {
return max;
}
round = (round === undefined) ? true : !!round;
var value = Math.random() * (max - min) + min;
return round ? Math.round(value) : value;
} catch (e) {
console.log(e.name + ": " + e.message);
throw e; // rethrow to inform unit tests
}
};
}());
console.log("\nNumber().randomWithinRange(0, 10): " + Number().randomWithinRange(0, 10));
randomBoolean = !!Number().randomWithinRange(0, 1);
console.log("randomBoolean = !!Number().randomWithinRange(0, 1): " + randomBoolean);
}());
/**
* Example: Some custom String utility methods added to the String prototype
*/
(function () {
var rawString;
/**
* Returns an encoded String
*
* var raw = "<@{Hello&/World}£\\<>";
* var encoded = raw.encodeEntities(); // "<@{Hello&/World}£\<>"
*
* @return {String} The encoded String
*/
String.method("encodeEntities", function () {
return function encodeEntities() {
var regExp, value = this;
regExp = /&/gi;
value = value.replace(regExp, "&");
regExp = /</gi;
value = value.replace(regExp, "<");
regExp = />/gi;
value = value.replace(regExp, ">");
regExp = /\(/gi;
value = value.replace(regExp, "(");
regExp = /\)/gi;
value = value.replace(regExp, ")");
regExp = /\[/gi;
value = value.replace(regExp, "[");
regExp = /\]/gi;
value = value.replace(regExp, "]");
regExp = /\{/gi;
value = value.replace(regExp, "{");
regExp = /\}/gi;
value = value.replace(regExp, "}");
regExp = /"/gi;
value = value.replace(regExp, """);
regExp = /“/gi;
value = value.replace(regExp, "“");
regExp = /”/gi;
value = value.replace(regExp, "”");
regExp = /'/gi;
value = value.replace(regExp, "'");
regExp = /‘/gi;
value = value.replace(regExp, "‘");
regExp = /’/gi;
value = value.replace(regExp, "’");
regExp = /\//gi;
value = value.replace(regExp, "/");
regExp = /\\/gi;
value = value.replace(regExp, "\");
regExp = /£/gi;
value = value.replace(regExp, "£");
regExp = /€/gi;
value = value.replace(regExp, "€");
regExp = /©/gi;
value = value.replace(regExp, "©");
regExp = /®/gi;
value = value.replace(regExp, "®");
regExp = /™/gi;
value = value.replace(regExp, "™");
regExp = /@/gi;
value = value.replace(regExp, "@");
return value;
};
}());
rawString = "<@{Hello&/World}£\\<>";
console.log("\nrawString: " + rawString + ", encodedString: " + rawString.encodeEntities());
/**
* Returns a decoded String, matches against entity code, number and name
*
* var raw = "<@{Hello&/World}£\<>";
* var decoded = raw.decodeEntities(); // "<@{Hello&/World}£\\<>"
*
* @return {String} The decoded String
*/
String.method("decodeEntities", function () {
return function decodeEntities() {
var regExp, value = this;
regExp = /(%26|&|&)/gi;
value = value.replace(regExp, "&");
regExp = /(%A0| | )/gi;
value = value.replace(regExp, " ");
regExp = /(%3C|<|<)/gi;
value = value.replace(regExp, "<");
regExp = /(%3E|>|>)/gi;
value = value.replace(regExp, ">");
regExp = /(%28|()/gi;
value = value.replace(regExp, "(");
regExp = /(%29|))/gi;
value = value.replace(regExp, ")");
regExp = /(%5B|[)/gi;
value = value.replace(regExp, "[");
regExp = /(%5D|])/gi;
value = value.replace(regExp, "]");
regExp = /(%7B|{)/gi;
value = value.replace(regExp, "{");
regExp = /(%7D|})/gi;
value = value.replace(regExp, "}");
regExp = /(%22|"|")/gi;
value = value.replace(regExp, "\"");
regExp = /(%93|“|“)/gi;
value = value.replace(regExp, "“");
regExp = /(%94|”|”)/gi;
value = value.replace(regExp, "”");
regExp = /(%27|'|')/gi;
value = value.replace(regExp, "'");
regExp = /(%91|‘|‘)/gi;
value = value.replace(regExp, "‘");
regExp = /(%92|’|’)/gi;
value = value.replace(regExp, "’");
regExp = /(%2F|/|⁄)/gi;
value = value.replace(regExp, "/");
regExp = /(%5C|\)/gi;
value = value.replace(regExp, "\\");
regExp = /(%A3|£|£)/gi;
value = value.replace(regExp, "£");
regExp = /(%80|€|€)/gi;
value = value.replace(regExp, "€");
regExp = /(%A9|©|©)/gi;
value = value.replace(regExp, "©");
regExp = /(%AE|®|®)/gi;
value = value.replace(regExp, "®");
regExp = /(%99|™|™|™)/gi;
value = value.replace(regExp, "™");
regExp = /(%40|@)/gi;
value = value.replace(regExp, "@");
return value;
};
}());
rawString = "<@{Hello&/World}£\<>";
console.log("\nrawString: " + rawString + ", decodedString: " + rawString.decodeEntities());
/**
* Trim whitespace
*
* var raw = " hello world ";
* var trimmed = raw.trim(); // "hello world"
*
* @return {String} The trimmed String
*/
String.method("trim", function () {
return this.replace(/^\s+|\s+$/g, "");
});
rawString = " hello world ";
console.log("\nrawString: " + rawString + ", trimmedString: " + rawString.trim());
/**
* Check if the String is empty
*
* "hello world".isEmpty() // false;
* "".isEmpty() // true;
* " ".isEmpty() // true
* "''".isEmpty() // false
*
* @return {Boolean}
*/
String.method("isEmpty", function () {
return this === "" || this.trim() === "";
});
console.log('\n"".isEmpty(): ' + "".isEmpty());
console.log('" ".isEmpty(): ' + " ".isEmpty());
console.log('" hello world ".isEmpty(): ' + " hello world ".isEmpty());
/**
* Check if the String contains traces of common HTML/XML tags
*
* "Hello World".containsTags() // false
* "Hello <strong>World</strong>".containsTags() // true
* "Hello <span class='earth'>World</span>".containsTags() // true
* 'Hello "> World'.containsTags() // true
* "Hello <p>World</p>".containsTags() // true
*
* @return {Boolean}
*/
String.method("containsTags", function () {
var searchTags = [
"</",
'/>',
'">',
"<span",
"<p",
"<br"
],
searchTagCount = searchTags.length;
return function containsTags() {
var i, value, tag;
if (!this.isEmpty()) {
value = this.decodeEntities().toLowerCase();
for (i = 0; i < searchTagCount; i += 1) {
tag = searchTags[i];
if (value.indexOf(tag) !== -1) {
return true;
}
}
}
return false;
};
}());
console.log('\n"Hello World".containsTags(): ' + "Hello World".containsTags());
console.log('"Hello <p>World</p>".containsTags(): ' + "Hello <p>World</p>".containsTags());
console.log('"Hello <span class=\"earth\">World</span>".containsTags(): ' + "Hello <span class=\"earth\">World</span>".containsTags());
console.log('"Hello \"> World".containsTags(): ' + "Hello \"> World".containsTags());
}());
/**
* Example: A custom Array utility method added to the Array prototype
*/
(function () {
var someArray = [
{data: 1},
{data: 2},
{data: 3},
{data: 4},
{data: 5}
];
/**
* Return an out of bounds index as if it wraps the Array length
*
* var someArray = [{data:0}, {data:1}, {data:2}, {data:3}, {data:4}];
* var wrappedNegative = someArray.wrappedIndex(-3); // 2
* var wrappedPositive = someArray.wrappedIndex(6); // 1
*
* @param {Number} index Index to wrap
*
* @return {Number} The wrapped index
*/
Array.method("wrappedIndex", function () {
return function wrappedIndex(index) {
try {
if (typeof index !== "number") {
throw new TypeError("wrappedIndex(...) requires a Number arg");
}
return (index % this.length + this.length) % this.length;
} catch (e) {
console.log(e.name + ": " + e.message);
throw e; // rethrow to inform unit tests
}
};
}());
console.log("\nsomeArray.length: " + someArray.length + ", someArray.wrappedIndex(6): " + someArray.wrappedIndex(6));
}());