css - 如何在 SASS 中创建一个可以接受键并返回所有祖先列表的递归函数?

标签 css function recursion sass sass-maps

我正在尝试创建一个 get-ancestors() 函数,它接受一个 $key 并返回列表中的所有祖先,如下所示:

$ancestors-map : (
    'button' : (),
     'small-button' : (
            'button'
    ),
    'hollow-button' : (
            'button',
    ),
    'small-hollow-button' : (
            'small-button',
            'hollow-button',
    )
);

调用 get-ancestors('small-hollow-button') 应该返回 ('small-button', 'button', 'hollow-button', 'button')

然后我想删除重复的祖先,但我应该能够解决这个问题。任何帮助将不胜感激。

编辑:我尝试了很多东西,最接近的是这样的:

@function get-ancestors($ancestors, $key) {
    $value: map-get($ancestors-map, $key);

    @if length($value) == 0 {
        @return $ancestors;
    }

    @each $ancestor in $value {
        @return get-parents($ancestors, $ancestor);
    }    
}

编辑:感谢您的回答,这是我的最终设置和扩展示例:

$ancestors: (
    'red' : (),
    'background-color' : ('red'),
    'button' : (),
    'red-bg' : ('background-color'),
    'small-button' : ('button'),
    'hollow-red-button' : ('button', 'red-bg'),
    'small-hollow-red-button' : ('small-button', 'hollow-red-button')
);

@function get-ancestors($key, $list: ()) {
  $key-list: map-get($ancestors, $key);

  @if length($key-list) == 0 { 
    $list: join($list, $key)
  } @else {
    @each $parent in $key-list {
      $list: get-ancestors($parent, $list);
    }
    $list: join($list, $key)
  }

  @return $list;
}

.cool {
  content: get-ancestors($key: 'small-hollow-red-button');
}

最佳答案

不是递归的,但我认为这就是您要找的。

DEMO

$ancestors-map: (
    'button' : (),
    'small-button' : ('button'),
    'hollow-button' : ('button'),
    'small-hollow-button' : ('small-button', 'hollow-button')
);

@function get-ancestors($ancestors, $key) {
  $key-list: map-get($ancestors, $key);
  @if length($key-list) == 0 { @return $ancestors; }

  $list: ();
  @each $parent in $key-list {
    $list: append($list, $parent, comma);
    $list: append($list, map-get($ancestors, $parent));
  }

  @return $list;
}

关于css - 如何在 SASS 中创建一个可以接受键并返回所有祖先列表的递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47447830/

相关文章:

recursion - 在函数式语言中,编译器如何将非尾递归转换为循环以避免堆栈溢出(如果有的话)?

html - 较小屏幕尺寸的 float 问题

javascript - 无法弄清楚如何返回回调函数 - 需要替代解决方案

在 C 中创建一个 sin 公式

javascript - 正则表达式将所有单词转为大写,但排除 '(撇号)

c++ - 递归打印 n, n-1, n-2,...3,2,1,2,3,...n

html - 调整浏览器大小时页面组件会重叠

CSS - 两列表单保持正确的选项卡顺序?

css - CSS 可以检测一个元素的子元素数量吗?

c - 尝试递归循环文件夹内容