From 6402af7db9b952b24f3099c2b59832dd19541cfd Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Sun, 24 Jul 2016 08:29:39 -0700 Subject: [PATCH] Use `String#slice` instead of `String#indexOf` for `_.endsWith` and `_.startsWith`. --- lodash.js | 6 ++++-- test/test.js | 27 +++++++++++---------------- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/lodash.js b/lodash.js index 6ec57f239..f717c2bdc 100644 --- a/lodash.js +++ b/lodash.js @@ -13703,8 +13703,9 @@ ? length : baseClamp(toInteger(position), 0, length); + var end = position; position -= target.length; - return position >= 0 && string.indexOf(target, position) == position; + return position >= 0 && string.slice(position, end) == target; } /** @@ -14152,7 +14153,8 @@ function startsWith(string, target, position) { string = toString(string); position = baseClamp(toInteger(position), 0, string.length); - return string.lastIndexOf(baseToString(target), position) == position; + target = baseToString(target); + return string.slice(position, position + target.length) == target; } /** diff --git a/test/test.js b/test/test.js index 585d5f047..bc5b4ad55 100644 --- a/test/test.js +++ b/test/test.js @@ -5393,14 +5393,6 @@ assert.strictEqual(_.endsWith(string, 'ab', 2.2), true); }); - - QUnit.test('should return `true` when `target` is an empty string regardless of `position`', function(assert) { - assert.expect(1); - - assert.ok(lodashStable.every([-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { - return _.endsWith(string, '', position, true); - })); - }); }()); /*--------------------------------------------------------------------------*/ @@ -20885,14 +20877,6 @@ assert.strictEqual(_.startsWith(string, 'bc', 1.2), true); }); - - QUnit.test('should return `true` when `target` is an empty string regardless of `position`', function(assert) { - assert.expect(1); - - assert.ok(lodashStable.every([-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity], function(position) { - return _.startsWith(string, '', position, true); - })); - }); }()); /*--------------------------------------------------------------------------*/ @@ -20924,9 +20908,20 @@ assert.expect(2); var position = isStartsWith ? 1 : 2; + assert.strictEqual(func(string, 'b', Object(position)), true); assert.strictEqual(func(string, 'b', { 'toString': lodashStable.constant(String(position)) }), true); }); + + QUnit.test('should return `true` when `target` is an empty string regardless of `position`', function(assert) { + assert.expect(1); + + var positions = [-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity]; + + assert.ok(lodashStable.every(positions, function(position) { + return func(string, '', position); + })); + }); }); /*--------------------------------------------------------------------------*/