Skip to content

Instantly share code, notes, and snippets.

@treasonx
Created February 27, 2015 16:33
Show Gist options
  • Save treasonx/dc3d8bdfa9cec3a842b4 to your computer and use it in GitHub Desktop.
Save treasonx/dc3d8bdfa9cec3a842b4 to your computer and use it in GitHub Desktop.
Hot or Not?
$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