I was trying to solve a coding challenge on Codewars. My solution passed all the tests except for one which says the following:
should be pure, i.e. not mutate the original array
Your function should not mutate the input array: expected [ 2, 5, 5, 7, 7, 10, 10, 10, 10, 10 ]
to deeply equal [ 2, 5, 3, 7, 1, 10, 4, 6, 8, 9 ]
.
Here is my solution to the challenge called: Bubblesort Once
function bubblesortOnce(a) {
let newArr = [];
for (let i = 0; i < a.length; i++) {
if (a[i] > a[i + 1]) {
newArr[i] = a[i + 1];
a[i + 1] = a[i];
} else {
newArr[i] = a[i];
}
}
return newArr;
}
Can anyone help me with this?
Your function should not mutate the input array
The Input array is the array passed into your function.
Mutation is another word for changing the value of something.
To stop changing the input array we can use the Spread operator (...) to copy each element of the input array into a new array, and then change that new array instead:
The below snippet utilises a new "passedArray" input which is then copied with the spread operator into a new array:
function bubblesortOnce(passedArray) {
let a = [...passedArray]; //copy the array
let newArr = [];
for (let i = 0; i < a.length; i++) {
if (a[i] > a[i + 1]) {
newArr[i] = a[i + 1];
a[i + 1] = a[i];
} else {
newArr[i] = a[i];
}
}
return newArr;
}