From ecf9304811a0fd54289a35b9c3b715a1d4447806 Mon Sep 17 00:00:00 2001 From: Georgios Kalpakas Date: Tue, 8 Sep 2015 11:58:19 +0300 Subject: [PATCH] fix(limitTo): start at 0 if `begin` is negative and exceeds input length Previously, specifying a negative `begin` whose abs value exceeds the input's length, would behave unexpectedly (depending on the value of `limit` relative to `begin`). E.g.: ``` limitToFilter('12345', 3, -7) === '1' // but limitToFilter('12345', 10, -7) === '123' ``` This commit fixes the unexpected behaviour, by setting `begin` to 0 in the aforementioned cases. Thus, the previous examples become: ``` limitToFilter('12345', 3, -7) === limitToFilter('12345', 3, 0) === '123' // and limitToFilter('12345', 10, -7) === limitToFilter('12345', 10, 0) === '12345' ``` Fixes #12775 Closes #12781 --- src/ng/filter/limitTo.js | 2 +- test/ng/filter/limitToSpec.js | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/ng/filter/limitTo.js b/src/ng/filter/limitTo.js index a42ec8caf40f..5f77d58d8f3d 100644 --- a/src/ng/filter/limitTo.js +++ b/src/ng/filter/limitTo.js @@ -111,7 +111,7 @@ function limitToFilter() { if (!isArray(input) && !isString(input)) return input; begin = (!begin || isNaN(begin)) ? 0 : toInt(begin); - begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin; + begin = (begin < 0) ? Math.max(0, input.length + begin) : begin; if (limit >= 0) { return input.slice(begin, begin + limit); diff --git a/test/ng/filter/limitToSpec.js b/test/ng/filter/limitToSpec.js index 343290a55c5d..a403c43b94ba 100644 --- a/test/ng/filter/limitToSpec.js +++ b/test/ng/filter/limitToSpec.js @@ -140,16 +140,19 @@ describe('Filter: limitTo', function() { it('should return an empty array if Y exceeds input length', function() { expect(limitTo(items, '3', 12)).toEqual([]); - expect(limitTo(items, 4, '-12')).toEqual([]); expect(limitTo(items, -3, '12')).toEqual([]); - expect(limitTo(items, '-4', -12)).toEqual([]); }); it('should return an empty string if Y exceeds input length', function() { expect(limitTo(str, '3', 12)).toEqual(""); - expect(limitTo(str, 4, '-12')).toEqual(""); expect(limitTo(str, -3, '12')).toEqual(""); - expect(limitTo(str, '-4', -12)).toEqual(""); + }); + + it('should start at 0 if Y is negative and exceeds input length', function() { + expect(limitTo(items, 4, '-12')).toEqual(['a', 'b', 'c', 'd']); + expect(limitTo(items, '-4', -12)).toEqual(['e', 'f', 'g', 'h']); + expect(limitTo(str, 4, '-12')).toEqual("tuvw"); + expect(limitTo(str, '-4', -12)).toEqual("wxyz"); }); it('should return the entire string beginning from Y if X is positive and X+Y exceeds input length', function() {