javascript - I don't understand a function, please give me some advice?
ringa_lee
ringa_lee 2017-07-05 10:54:47
0
2
745
function choose(arr, size) {
  var allResult = [];

  (function (arr, size, result) {
    var arrLen = arr.length;
    if (size > arrLen) {
      return;
    }
    if (size == arrLen) {
      allResult.push([].concat(result, arr))
    } else {
      for (var i = 0; i < arrLen; i++) {
        var newResult = [].concat(result);
        newResult.push(arr[i]);

        if (size == 1) {
          allResult.push(newResult);
        } else {
          var newArr = [].concat(arr);
          newArr.splice(0, i +  1);
          arguments.callee(newArr, size - 1, newResult);
        }
      }
    }
  })(arr, size, []);

  return allResult;
}
ringa_lee
ringa_lee

ringa_lee

reply all(2)
女神的闺蜜爱上我

This is a permutation and combination implementation using black magic. The functions achieved are roughly:

  • choose([1, 2, 3], 1) gets [ [ 1 ], [ 2 ], [ 3 ] ]

  • choose([1, 2, 3], 2) gets [ [ 1, 2 ], [ 1, 3 ], [ 2, 3 ] ]

  • choose([1, 2, 3, 4], 3) gets [ [ 1, 2, 3 ], [ 1, 2, 4 ], [ 1, 3, 4 ], [ 2, 3, 4 ] ]

The inner anonymous function calls itself recursively through arguments.callee. Each time it recursively calls itself, the size parameter is reduced by one. Each newResult is a [length is the total number of combinations, and each element is the current combination. ] is a two-dimensional array. When the length of each item in newResult reaches size, the recursion ends and the final result is returned.

洪涛

Closure writing method prevents the internal parameters of the function from being affected by external factors.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template