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

后端 未结 3 1557
一整个雨季
一整个雨季 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

    Easy way to make immutable object in JS is to use Object.freeze.

    I created your input array as:

    const array1 = Object.freeze([
        Object.freeze([ 1, 2 ]),
        Object.freeze([ 3, 4 ])
    ])
    

    Then, when I tried to call your function I got:

    Uncaught TypeError: Cannot add/remove sealed array elements
    at Array.shift ()
    at arr.reduce (:7:38)
    at Array.reduce ()
    at roundRobin (:4:28)
    at :6:17
    

    You're using shift, which is mutating orignal array.

    Replace it with Array.slice(0,1)[0] and it will start working.

提交回复
热议问题