Skip to content

Commit

Permalink
Add startsWith/endsWith from sugar.js trunk
Browse files Browse the repository at this point in the history
  • Loading branch information
esprehn committed Jul 29, 2014
1 parent c9f7634 commit f24744f
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions ui/base.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,60 @@

// Borrowed from sugar.js HEAD since startsWith/endsWith were very slow when
// they supported regexps.
(function() {
function getCoercedStringSubject(obj) {
if(obj == null) {
throw new TypeError();
}
return String(obj);
}

function getCoercedSearchString(obj, errorOnRegex) {
if(errorOnRegex && obj instanceof RegExp) {
throw new TypeError();
}
return String(obj);
}

String.prototype.startsWith = function(searchString) {
var str, start, pos, len, searchLength, position = arguments[1];
str = getCoercedStringSubject(this);
searchString = getCoercedSearchString(searchString, true);
pos = Number(position) || 0;
len = str.length;
start = Math.min(Math.max(pos, 0), len);
searchLength = searchString.length;
if(searchLength + start > len) {
return false;
}
if(str.substr(start, searchLength) === searchString) {
return true;
}
return false;
};

String.prototype.endsWith = function(searchString) {
var str, start, end, pos, len, searchLength, endPosition = arguments[1];
str = getCoercedStringSubject(this);
searchString = getCoercedSearchString(searchString, true);
len = str.length;
pos = len;
if(endPosition != undefined) {
pos = Number(endPosition) || 0;
}
end = Math.min(Math.max(pos, 0), len);
searchLength = searchString.length;
start = end - searchLength;
if(start < 0) {
return false;
}
if(str.substr(start, searchLength) === searchString) {
return true;
}
return false;
};
})();

// Polymer provides this, but we add it just in case so you can use models
// without polymer.
if (!NodeList.prototype.array) {
Expand Down

0 comments on commit f24744f

Please sign in to comment.