RoundRobin functional approach - why does my function have side effects?

后端 未结 3 1567
一整个雨季
一整个雨季 2021-02-14 09:31

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

3条回答
  •  佛祖请我去吃肉
    2021-02-14 10:09

    Array#shift is doing the mutating.

    var array = [0, 1, 2, 3, 4];
    array.shift(); // -> 0
    array; // -> [1, 2, 3, 4];
    

    The easiest way around that is to clone the array. Usually that can be done with Array#concat but since your arrays are nested (though simple) you can do this:

    const roundRobin = (arr, results) => {
        arr = JSON.parse(JSON.stringify(arr));
        if (arr.length === 0) return results;
        // ...
    

    If you're concerned that the global JSON makes the function impure, you can abstract that out.

    const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
    roundRobin(deepClone(array), []);
    

提交回复
热议问题