0

我正在尝试创建一个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');
}
4

1 回答 1

0

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

演示

$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;
}
于 2017-11-24T11:26:50.293 回答