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

后端 未结 3 1552
一整个雨季
一整个雨季 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 10:00

    1. If I am using reduce, which is pure, how am I mutating my parameters?

    Function parameters can't really be mutated; a strange thought – but I'm sure you meant the arguments supplied to your function are being mutated. And yeah, that's with .shift as others pointed out

    And for what it's worth, .reduce isn't pure unless the user-supplied lambda is pure

    1. Is there another pure/functional way of implementing roundRobin?

    Yep

    const isEmpty = xs =>
      xs.length === 0
      
    const head = ( [ x , ...xs ] ) =>
      x
      
    const tail = ( [ x , ...xs ] ) =>
      xs
    
    const append = ( xs , x ) =>
      xs.concat ( [ x ] )
      
    const roundRobin = ( [ x , ...xs ] , acc = [] ) =>
      x === undefined
        ? acc
        : isEmpty ( x )
          ? roundRobin ( xs , acc )
          : roundRobin ( append ( xs , tail ( x ) )
                       , append ( acc , head ( x ) )
                       )
    
    const data =
      [ [ 1 , 4 , 7 , 9 ]
      , [ 2 , 5 ]
      , [ 3 , 6 , 8 , 10 , 11 , 12 ]
      ]
                       
    console.log ( roundRobin ( data ) )
    // => [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ]
    
    console.log ( roundRobin ( [ [ 1 , 2 , 3 ] ] ) )
    // => [ 1 , 2 , 3 ]
    
    console.log ( roundRobin ( [] ) )
    // => []

提交回复
热议问题