-
Notifications
You must be signed in to change notification settings - Fork 28
/
polyfill.js
51 lines (44 loc) · 1.29 KB
/
polyfill.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
'use strict';
Array.prototype.findAll = function(fn) {
var arr = [];
this.forEach(function(i) {
if (fn(i)) {
arr.push(i);
}
});
return arr;
};
Array.prototype.randomElement = function() {
return this[Math.floor(Math.random() * this.length)];
};
Array.prototype.link = function(i, url) {
url = url.format(this);
if (url.startsWith('/')) { // internal links
var link = '<a href="{0}">{1}</a>';
} else if (url.includes('//')) { // external links
var link = '<a href="{0}" target="_blank">{1}</a>';
} else {
var link = '<a onclick="{0}">{1}</a>';
}
return (this[i] = link.format([url, this[i]]));
};
String.prototype.format = function(args) {
return this.replace(/{(\w+)}/g, function(match, key) {
return typeof args[key] != 'undefined'? args[key]: match;
});
};
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(s, position) {
return this.substr(position || 0, s.length) === s;
};
}
if (!String.prototype.includes) {
String.prototype.includes = function(s, position) {
return this.indexOf(s, position || 0) !== -1;
};
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}