raghu nath
raghu nath

Reputation: 65

Sass: Return list values with unique characters only

Can anyone provide a function to return values from a list only if they do not contain duplicate characters ?

For example, Lets say that I have list with values as $list: (aa, bb, cd, ef);

Expected output:

(cd, ef);

This is the code I have got so far. It does not solve my issue at all, but after multiple trials, this is all I could get.

@function dupChars($list, $separator: comma) {

  $result: null;
  $temp: null;

  @each $item in $list {

    @for $i from 1 through str-length($item) {

      @if not index($temp, str-slice($item, $i, $i)) {

        $temp: append($temp, #{str-slice($item, $i, $i)}, $separator);
      }
    }
  }

  $result: append($result, $temp, $separator);

  @return $result;
}

$list: (aa, bb, cd, ef);

/* #{dupChars($list)} */

Obtained output:

a, b, c, d, e, f

Upvotes: 1

Views: 182

Answers (1)

ReSedano
ReSedano

Reputation: 5060

To try to resolve this, I found that a way could be check for every items how many same singole letter there are in it (using a double @for loop).

For example, imagine to have this list: abc. If the result is 3 (the length of my item) I know that every letter is only once in that item, then there is no duplicates (3 = 3).

a -- a // 1
a -- b
a -- c
b -- a
b -- b // 2
b -- c
c -- a
c -- b
c -- c // 3

Another example. Now our list is aab. The result is bigger than the length of my item so we have duplicates (5 > 3)

a -- a // 1
a -- a // 2
a -- b 
a -- a // 3
a -- a // 4
a -- b
b -- a
b -- a
b -- b // 5

So when the number is bigger than my item's length, I don't append that $temp to my $result

The code:

@function dupChars($list, $separator: comma) {
    $result: null;
    $temp: null;

    @each $item in $list {
        $var: 0;
        @for $i from 1 through length($item) {

            @for $j from 1 through (str-length($item)) {

                @for $k from 1 through (str-length($item)) {
                    //@debug str-slice($item, $j, $j) + "---" + str-slice($item, $k, $k) ;

                    @if (str-slice($item, $j, $j) == str-slice($item, $k, $k)) {
                        $var: $var + 1;
                    }
                }
            }
        }
        @if($var <= str-length($item)){
          $temp: append($temp, #{$item}, $separator);
        }
    }

    $result: append($result, $temp, $separator);

    @return $result;
}

$lista: (aa, bb, cd, ef);

div{content: dupChars($lista)};

The output:

div {
  content: cd, ef;
}

Upvotes: 1

Related Questions