Created
February 27, 2015 16:33
-
-
Save treasonx/dc3d8bdfa9cec3a842b4 to your computer and use it in GitHub Desktop.
Hot or Not?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$scope.shortenInText = function () { | |
var text = $scope.content.text || ''; | |
var PROTO_PTRN = /^https?:\/\//; | |
var tokens = text.split(/\s/); | |
_.chain(tokens) | |
// get tokens that look like URLs | |
.map(function(token) { | |
if(PROTO_PTRN.test(token)) { | |
return token; | |
} | |
}) | |
// remove duplicates | |
.unique() | |
// remove falsy values | |
.compact() | |
// make requests | |
.map(function (url) { | |
return shortenLink(url).then(function (shortLink) { | |
return { | |
original: url, | |
shortLink: shortLink | |
}; | |
}); | |
}) | |
// wait for all requests to complete | |
.tap(function (promises) { | |
return when.all(promises); | |
}) | |
.value() | |
// update text content with short links | |
.then(function (items) { | |
$scope.$apply(function ($s) { | |
var text = $s.content.text || ''; | |
_.each(items, function (item) { | |
var ptrn = new RegExp(_.escapeRegExp(item.original), 'g'); | |
text = text.replace(ptrn, item.shortLink); | |
}); | |
$s.content.text = text; | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment