2017-11-23 2 views
0

Ich versuche, eine get-ancestors() Funktion zu schaffen, wie dies ein $key und gibt alle Vorfahren in einer Liste nimmt:Wie erstellt man eine rekursive Funktion in SASS, die einen Schlüssel akzeptiert und eine Liste aller Vorfahren zurückgibt?

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

get-ancestors('small-hollow-button') Aufruf ('small-button', 'button', 'hollow-button', 'button')

zurückkehren soll ich duplizierten Vorfahren dann entfernen möchte, aber Ich sollte das herausfinden können. Jede Hilfe würde sehr geschätzt werden.

Edit: Ich habe viele Dinge ausprobiert, und das nächste, was ich bekam, war mit so etwas wie folgt aus:

@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: Danke für die Antwort, hier ist meine letzte Setup mit einem erweiterten Beispiel:

$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'); 
} 

Antwort

0

Nicht rekursiv, aber ich denke, das ist, was Sie suchen.

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; 
} 
+0

Dies war in der Nähe, und schließlich zu meiner vollsten Lösung führen. Vielen Dank! – ungluck

Verwandte Themen