I'm using Sass (v3.3.0.alpha.392), and I have a multi-dimensional list that looks somewhat like this,
$list: (
config: (
foo: (
a: 1,
b: 2,
),
bar: (
a: 3,
b: 4,
),
));
I have a @mixin that takes an argument, and will output based on which argument is passed if it exists in the config $list. Something like this,
@mixin foo($arg) {
@if $arg exists in $list == true { // is 'foo' or 'bar'
// Do something
} @else {
@warn "failed.";
}
}
Usage,
.test {
@include foo(bar); // should return true and run code block
@include foo(data); // should return false and @warn
}
But, I cannot find the correct function to check if $arg exists in $list. I have tried small functions that check the index,
@function exists($n) {
@return (false == index($list, config $n));
}
But, this don't seem to work (I might just be using it incorrectly). I basically need this to switch between different operations based on if the arg is contained in the $list.
Also, might be a double question, but is there also any way to check if the $arg is an integer or string? Would also be very helpful.
Thanks!
Your $list is actually a map:
type-of($list) == map
And if I understand correctly, you are interested in matching your keys to a value (e.g. bar).
There is a function called map-has-key($map, $key) that returns true if it finds the matching key, but in a multidimensional map it only matches keys in the topmost level. However, you can write a simple wrapper function that recursively apply map-has-key through all the levels of your map until it finds a match. The wrapper function could be something like this:
@function rmhk($m, $a){
@if map-has-key($m, $a) { @return true; };
@each $key,$e in $m {
@if (type-of($e) == map) and rmhk($e, $a) { @return true; }
}
@return false;
}
The same way (with a recursive function) you can also match the values in your map in addition to the keys or traverse a list instead of a map (DEMO with value-matching in a multidimensional list).
And, as already pointed out by @Jeremy, you can use type-of() to check for the type of a variable (like string,number,list,map,color), but if for some reason you need to check for something more specific you would need a custom function (for example, this short function for checking if a value is an integer: DEMO).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With