I am trying to create a get-ancestors()
function that takes a $key
and returns all ancestors in a list like this:
$ancestors-map : (
'button' : (),
'small-button' : (
'button'
),
'hollow-button' : (
'button',
),
'small-hollow-button' : (
'small-button',
'hollow-button',
)
);
Calling get-ancestors('small-hollow-button')
should return ('small-button', 'button', 'hollow-button', 'button')
I would like to then remove duplicated ancestors, but I should be able to figure that out. Any help would be much appreciated.
Edit: I have tried many things, and the closest I got was with something like this:
@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);
}
}
Edit: Thanks for the answer, here's my final setup with an expanded example:
$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');
}