Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
set of underscore.js mixins, including, most importantly, a function to parse the link header for paging (a la the Github API). ParseLinkHeader is the javascript version of Github's PageLinks Java method => http://bit.ly/L71lRb
_.mixin({
capitalize: function(string) {
return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
},
startsWith: function(string, start) {
return string.slice(0, start.length) == start;
},
endsWith: function(string, end) {
return string.slice(-end.length) == end;
},
parseLinkHeader: function(string) {
paging = {};
if (string !== null) {
var links = string.split(',');
for (var i = 0, len = links.length; i < len; i++) {
var segments = links[i].split(';');
if (segments.length < 2)
continue;
var linkPart = segments[0].trim();
if (!this.startsWith(linkPart, "<") || !this.endsWith(linkPart, ">"))
continue;
linkPart = linkPart.substring(1, linkPart.length - 1);
for (var j = 0, seg_len = segments.length; j < seg_len; j++) {
var rel = segments[j].trim().split("=");
if (rel.length < 2)
continue;
var relValue = rel[1];
if (this.startsWith(relValue, "\"") && this.endsWith(relValue, "\""))
relValue = relValue.substring(1, relValue.length - 1);
if (relValue == 'first')
paging.first = linkPart;
else if (relValue == 'last')
paging.last = linkPart;
else if (relValue == 'next')
paging.next = linkPart;
else if (relValue == 'prev')
paging.prev = linkPart;
}
}
}
return paging;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment