user2882335 user2882335 - 26 days ago 17
Sass (Sass) Question

sass mixin parameters - check for patterns

How can I check if all parameters passed to a mixin are the same value?

pseudo code:

@mixin cols($width...) {
@if (all $width values are the same) {
// do something
}
}

.three-cols {
@include cols(4,4,4);
}

Answer

I delegated the task of checking to see if the values are equal to a function which can then be called from the mixin so that they both have single responsibility.

@function check_values($values...) {
  $counter: 0;
  @if ( nth($values, 1) != nth($values,2) ) {
    $counter: 0;
  }
  @else {
    $counter: $counter + 1;
    @for $i from 2 to length($values) {
      $counter: if(nth($values, $i) == nth($values, $i + 1), $counter + 1, $counter );
    }
  }
  @return if($counter + 1 == length($values), true, false)
}

The function returns either true or false and can be used on any number of args

@debug check_values(2,2,1,1,2,2); //false
@debug check_values(2,2,2); //true
@debug check_values(2,2,2,1); //false

The function just needs to be called in the mixin

@mixin cols($width...) {
  @if ( check_values($width...) ) {
    // do something
  }
}

Hope this helps

Comments