Skip to content

Commit fec30dc

Browse files
authored
Ensure same reference is returned for no-op take/skip/takeLast/skipLast (immutable-js#1077)
Also generalizes the concept to reify() to ensure a reify'd no-op returns the same reference. Fixes immutable-js#1046
1 parent 0f33f4e commit fec30dc

File tree

5 files changed

+44
-26
lines changed

5 files changed

+44
-26
lines changed

__tests__/List.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,24 @@ describe('List', () => {
457457
expect(r.toArray()).toEqual(['c', 'd']);
458458
});
459459

460+
it('takes and skips no-ops return same reference', () => {
461+
var v = List.of('a', 'b', 'c', 'd', 'e', 'f');
462+
var r = v.skip(0).take(6);
463+
expect(r).toBe(v);
464+
});
465+
466+
it('takeLast and skipLast values', () => {
467+
var v = List.of('a', 'b', 'c', 'd', 'e', 'f');
468+
var r = v.skipLast(1).takeLast(2);
469+
expect(r.toArray()).toEqual(['d', 'e']);
470+
});
471+
472+
it('takeLast and skipLast no-ops return same reference', () => {
473+
var v = List.of('a', 'b', 'c', 'd', 'e', 'f');
474+
var r = v.skipLast(0).takeLast(6);
475+
expect(r).toBe(v);
476+
});
477+
460478
it('efficiently chains array methods', () => {
461479
var v = List.of(1,2,3,4,5,6,7,8,9,10,11,12,13,14);
462480

dist/immutable.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3557,7 +3557,7 @@
35573557
// #pragma Helper Functions
35583558

35593559
function reify(iter, seq) {
3560-
return isSeq(iter) ? seq : iter.constructor(seq);
3560+
return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq);
35613561
}
35623562

35633563
function validateEntry(entry) {
@@ -4611,11 +4611,11 @@
46114611
},
46124612

46134613
skip: function(amount) {
4614-
return this.slice(Math.max(0, amount));
4614+
return amount === 0 ? this : this.slice(Math.max(0, amount));
46154615
},
46164616

46174617
skipLast: function(amount) {
4618-
return reify(this, this.toSeq().reverse().skip(amount).reverse());
4618+
return amount === 0 ? this : this.slice(0, -Math.max(0, amount));
46194619
},
46204620

46214621
skipWhile: function(predicate, context) {
@@ -4635,7 +4635,7 @@
46354635
},
46364636

46374637
takeLast: function(amount) {
4638-
return reify(this, this.toSeq().reverse().take(amount).reverse());
4638+
return this.slice(-Math.max(0, amount));
46394639
},
46404640

46414641
takeWhile: function(predicate, context) {

0 commit comments

Comments
 (0)