具有目标长度的列表中所有组合的Scss递归函数

时间:2019-10-04 15:24:56

标签: sass

谁能将此函数变成递归的通用函数,以便我可以用它来检索n个大小的组合?

这是我目前拥有的,并且只能在$size: 2

之前有效
@function combinations($list, $size, $separator: comma){
  $result: null;

  @each $item in $list {

    @if ($size == 1) {

      $result: append($result, #{$item}, $separator);
    } @else {

      @each $val in $list {

        $result: join($result, #{$item}#{$val}, $separator);
      }
    }
  }

  @return $result;
}


$list: a, b, c;

test {
  val: combinations($list, 2);
}

输出尺寸:1

  

a,b,c

尺寸输出:2

  

a,b,c,aa,ab,ac,ba,bb,bc,ca,cb,cc

但是我需要继续$size: nn <= length($list)

1 个答案:

答案 0 :(得分:1)

经过多次尝试和大量研究,我终于找到了解决方案。

@function combinations($list, $size: length($list), $combs: (), $separator: comma){

  @if ($combs == ()) {
    $combs: $list;
  }

  @if ($size == 1) {

    @return $combs
  }

  $newCombs: null;

  @each $comb in $combs {
    @each $item in $list {
      @if not index($newCombs, $comb) {
        $newCombs: join($newCombs, #{$comb}#{$item}, $separator);
      }
    }
  }

  @return join($combs, #{combinations($list, abs($size - 1), $newCombs)});
}

$list: a, b, c;
$size: n;

combinations($list, $size);将基于$list输出$size中所有可能的值组合的列表。

相关问题