assert.deepStrictEqual(getLastN([1, 2, 3, 4, 5], 2), [4, 5]);
assert.deepStrictEqual(getLastN([1, 2, 3], 0), []);
This function is supposed to return the last n items of an array, but it returns an empty array instead. Fix the bug.
bug_typelogic
function getLastN(items: number[], n: number): number[] {
return items.slice(items.length - n);
}function getLastN(items: number[], n: number): number[] {
return items.slice(-n, 0);
}slice(-n, 0) always produces an empty array because the end index 0 is before the start index counted from the end. Using items.length - n as the start index (and omitting the end index, which defaults to the array's length) correctly returns the last n elements.