Skip to content

Commit

Permalink
Add position support as per ECMA-262 spec; Fixes gearcase#3
Browse files Browse the repository at this point in the history
  • Loading branch information
acagastya committed Oct 1, 2020
1 parent 4a75caf commit 40346d6
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ npm-debug.log*

/node_modules
/test/coverage
yarn.lock
18 changes: 15 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

module.exports = function (str, prefix) {
module.exports = function (str, prefix, pos) {

if (typeof prefix === 'undefined' || prefix === null) {
return false;
Expand All @@ -9,11 +9,23 @@ module.exports = function (str, prefix) {
str = String(str);
prefix = String(prefix);

if(pos === undefined || pos < 0) {
pos = 0;
}
else {
pos = +pos || 0;
}

var l = prefix.length;
var i = -1;
var i = pos - 1;
var j = 0;

if (i > str.length) {
return false;
}

while (++i < l) {
if (str.charAt(i) !== prefix.charAt(i)) {
if (str.charAt(i) !== prefix.charAt(j++)) {
return false;
}
}
Expand Down
20 changes: 20 additions & 0 deletions test/spec/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,24 @@ describe('start-with: ', function () {
it('startWith(\'abc\', \'bc\') => false', function () {
expect(startWith('abc', 'bc')).to.equal(false);
});

it('startWith(\'abc\', \'bc\', -1) => false', function () {
expect(startWith('abc', 'abc', -1)).to.equal(true);
});

it('startWith(\'abc\', \'bc\', 1) => false', function () {
expect(startWith('abc', 'bc', 1)).to.equal(true);
});

it('startWith(\'abc\', \'abc\', 10) => false', function () {
expect(startWith('abc', 'abc', 10)).to.equal(false);
});

it('startWith(\'abc\', \'abc\', \'foo\') => false', function () {
expect(startWith('abc', 'abc', 'foo')).to.equal(true);
});

it('startWith(\'abc\', \'abcd\') => false', function () {
expect(startWith('abc', 'abcd')).to.equal(false);
});
});

0 comments on commit 40346d6

Please sign in to comment.