|
| 1 | +import '@/app/2619-array-prototype-last'; |
| 2 | + |
| 3 | +describe('Problem 2619: Array.prototype.last', () => { |
| 4 | + test('last returns last element for non-empty arrays', () => { |
| 5 | + expect([1, 2, 3].last()).toBe(3); |
| 6 | + expect(['a', 'b', 'c'].last()).toBe('c'); |
| 7 | + expect([true, false].last()).toBe(false); |
| 8 | + }); |
| 9 | + |
| 10 | + test('last returns -1 for empty arrays', () => { |
| 11 | + expect([].last()).toBe(-1); |
| 12 | + expect(([] as number[]).last()).toBe(-1); |
| 13 | + }); |
| 14 | + |
| 15 | + test('last works after array mutations', () => { |
| 16 | + const arr = [10, 20]; |
| 17 | + expect(arr.last()).toBe(20); |
| 18 | + arr.push(30); |
| 19 | + expect(arr.last()).toBe(30); |
| 20 | + arr.pop(); |
| 21 | + expect(arr.last()).toBe(20); |
| 22 | + arr.splice(0, arr.length); |
| 23 | + expect(arr.last()).toBe(-1); |
| 24 | + }); |
| 25 | + |
| 26 | + test('last does not modify the array', () => { |
| 27 | + const arr = [5, 6, 7]; |
| 28 | + const before = [...arr]; |
| 29 | + arr.last(); |
| 30 | + expect(arr).toEqual(before); |
| 31 | + }); |
| 32 | + |
| 33 | + test('last is available on all array instances', () => { |
| 34 | + class MyArray extends Array<number> {} |
| 35 | + const myArr = new MyArray(1, 2, 3); |
| 36 | + expect(myArr.last()).toBe(3); |
| 37 | + }); |
| 38 | +}); |
0 commit comments