Skip to content

#223 Mutating Arrays

Adam Kubiś edited this page Oct 28, 2026 · 1 revision

223 Mutating Arrays

Suppose I want to define a function that removes the last element of an array each time I call it, but does not mutate the original array.

Fix the code so that the results are no longer mutating the array.

Current source and tests | Catalog | Testing and tooling

Run this solution

From the cloned repository root, after installing dependencies:

node "Edabit/223 Mutating Arrays.js"

Assertions are kept alongside the implementation and throw on failure. A successful run exits with code 0. Run every exercise with npm test or both lint and tests with npm run check.

Current implementation and tests

This is the complete executable file, including its imports and inline test cases. Run it from the repository, not as an isolated file copied out of the wiki. Line endings and trailing whitespace are normalized; executable tokens are unchanged.

//Suppose I want to define a function that removes the last element of an array each time I call it, but does not mutate the original array.
//Fix the code so that the results are no longer mutating the array.
function minusOne(arr) {
    return arr.slice(0, -1);
}
import { assertEquals } from '../testHelper.js';
const x = [1, 2, 3, 4, 5]
assertEquals(minusOne(x), [1, 2, 3, 4])
assertEquals(minusOne(x), [1, 2, 3, 4])
assertEquals(minusOne(x), [1, 2, 3, 4])
assertEquals(minusOne(x), [1, 2, 3, 4])
assertEquals(minusOne(x), [1, 2, 3, 4])

Clone this wiki locally