-
Notifications
You must be signed in to change notification settings - Fork 0
/
shorturl.js
66 lines (53 loc) · 1.53 KB
/
shorturl.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
const SHORTURL_EXPANDER_URL = 'http://litl-birdie.appspot.com/expand_shorturl';
const SHORTURL_PROVIDERS = ['http://bit.ly', 'http://is.gd', 'http://tinyurl.com'];
function ShortUrlExpander() {
this._init();
}
ShortUrlExpander.prototype = {
_init: function() {
this._expandedUrls = {};
},
isShort: function(url) {
for (var i = 0; i < SHORTURL_PROVIDERS.length; i++) {
if (url.indexOf(SHORTURL_PROVIDERS[i]) == 0) {
return true;
}
}
return false;
},
fetch: function(urls) {
for (var i = 0; i < urls.length; i++) {
if (this.isShort(urls[i]))
this.fetchOne(urls[i]);
}
},
fetchOne: function(url, callback) {
if (this.getExpandedUrl(url)) {
if (callback)
callback(this.getExpandedUrl(url));
return;
}
var me = this;
$.ajax({
method: 'GET',
url: SHORTURL_EXPANDER_URL,
data: {
shortUrl: url
},
dataType: 'text',
success: function(data) {
me._expandedUrls[url] = data;
if (callback)
callback(data);
},
error: function(data) {
if (callback)
callback(null);
}
});
},
getExpandedUrl: function(url) {
return this._expandedUrls[url];
},
}
var shorturls = new ShortUrlExpander();