Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
fix(limitTo): start at 0 if begin is negative and exceeds input length
Browse files Browse the repository at this point in the history
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
  • Loading branch information
gkalpak committed Oct 6, 2015
1 parent 216724b commit 4fc40bc
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/ng/filter/limitTo.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
11 changes: 7 additions & 4 deletions test/ng/filter/limitToSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit 4fc40bc

Please sign in to comment.