RoundRobin 函数方法 - 为什么我的函数有副作用?

2023-12-23

客观的

我正在尝试创建一个循环算法(https://en.wikipedia.org/wiki/Round-robin_scheduling https://en.wikipedia.org/wiki/Round-robin_scheduling)以纯函数的方式。

该函数应该接收一个如下所示的数组:

[
    [ 1, 2 ],
    [ 3, 4 ]
]

并产生以下输出:

[ 1, 3, 2, 4 ]

Code

为了实现这一目标,我决定递归地实现循环法,如下所示:

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);
};

在这里,我摸索出了一系列结果,当我没有什么可补充的时候,我就完成了。人们可以像下面这样使用这段代码:

const array =     [
        [ 1, 2 ],
        [ 3, 4 ]
    ];

const result = roundRobin( array, [] );

Problem

在我的代码中我使用reduce in my arr参数以确保我不会修改原始参数。但是,如果我在使用 roundRobin 之前和之后打印数组,则变量会更改!我以某种方式改变了它!

问题:

  1. 如果我使用的是纯粹的reduce,我该如何改变我的参数呢?
  2. 是否有另一种纯/函数式方式来实现 roundRobin?

  1. 如果我使用的是纯粹的reduce,我该如何改变我的参数呢?

功能参数无法真正变异;一个奇怪的想法——但我确信你的意思是论点提供给你的函数正在被改变。是的,那就是.shift正如其他人指出的

就其价值而言,.reduce除非用户提供的 lambda 是纯的,否则不是纯的

  1. 是否有另一种纯/函数式方式来实现 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 ( [] ) )
// => []
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RoundRobin 函数方法 - 为什么我的函数有副作用? 的相关文章

随机推荐