Objective
I am trying to create a Round Robin algorithm ( https://en.wikipedia.org/wiki/Round-robin_scheduling ) in a pure functional way.
This function, is supposed to received an array like the following:
[
[ 1, 2 ],
[ 3, 4 ]
]
And produce the following output:
[ 1, 3, 2, 4 ]
Code
To achieve this, I decided to implement round robin recursively like the following:
const roundRobin = (arr, results) => {
if (arr.length === 0) return results;
const newResults = arr.reduce((acc, current) => {
if (current.length > 0) {
acc.results.push(current.shift());
acc.arr.push(current);
}
return acc;
}, { arr: [], results });
return roundRobin(newResults.arr, newResults.results);
};
Here, I feel up an array of results, and I finish when I have nothing left to add to it. One would use this code like the following:
const array = [
[ 1, 2 ],
[ 3, 4 ]
];
const result = roundRobin( array, [] );
Problem
In my code I am using reduce
in my arr
parameter to ensure I don't modify the original. However, if I print array before using roundRobin and after, the variable is changed ! I mutate it somehow!
Questions:
- If I am using reduce, which is pure, how am I mutating my parameters?
- Is there another pure/functional way of implementing roundRobin?