Skip to content

Instantly share code, notes, and snippets.

@ethertank
Created January 1, 2013 00:23
Show Gist options
  • Save ethertank/4424136 to your computer and use it in GitHub Desktop.
Save ethertank/4424136 to your computer and use it in GitHub Desktop.
(function(SP) {
SP.endsWith || (SP.endsWith = function(str, pos) {
pos = (pos === undefined) ? this.length : Math.floor(+pos);
str = str.toString();
var start = Math.min(Math.max(pos, 0), this.length) - str.length;
if (start < 0) return !1;
var idx = ''.indexOf.call(this, str, start);
return idx === start;
});
})(String.prototype);
function assertEq(fn, val) {
console.log(fn === val);
}
assertEq("abc".endsWith("abc"), true);
assertEq("abcd".endsWith("bcd"), true);
assertEq("abc".endsWith("c"), true);
assertEq("abc".endsWith("abcd"), false);
assertEq("abc".endsWith("bbc"), false);
assertEq("abc".endsWith("b"), false);
assertEq("abc".endsWith("abc", 3), true);
assertEq("abc".endsWith("bc", 3), true);
assertEq("abc".endsWith("a", 3), false);
assertEq("abc".endsWith("bc", 3), true);
assertEq("abc".endsWith("a", 1), true);
assertEq("abc".endsWith("abc", 1), false);
assertEq("abc".endsWith("b", 2), true);
assertEq("abc".endsWith("d", 2), false);
assertEq("abc".endsWith("dcd", 2), false);
assertEq("abc".endsWith("a", 42), false);
assertEq("abc".endsWith("bc", Infinity), true); //*****
assertEq("abc".endsWith("a", Infinity), false);
assertEq("abc".endsWith("bc", undefined), true);
assertEq("abc".endsWith("bc", -43), false);
assertEq("abc".endsWith("bc", -Infinity), false);
assertEq("abc".endsWith("bc", NaN), false); //*****
// イマイチわかってない。取りあえず切り捨て。
assertEq("abc".endsWith("a", 1.1), true);
assertEq("abc".endsWith("a", "1.1"), true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment