D
D
dom1n1k2018-02-14 00:44:36
Layout
dom1n1k, 2018-02-14 00:44:36

What is the best way to handle associative arrays in SASS?

SASS has associative arrays (maps). The thing is certainly useful - it would be if it were not for the ugly syntax of using it:
map-get($map, $key)
Who could have thought of such a thing, I don’t know. And okay, if I have a one-dimensional array. And if two-dimensional or God forbid three? Well, something like:

$button-color: (
    primary: (
        normal: (
            background: #0088cc,
            text: #ffffff,
        ),
        hover: (
            background: #0077b3,
            text: #ffffff,
        ),
    ),
    default: (
        // ...
    ),
);

// wtf?
background-color: map-get(map-get(map-get($button-color, 'primary'), 'hover'), 'background');

Well, you can, of course, write some kind of wrapper function or mixin. But in my opinion, this will not eliminate the problem, but only smooth it out a little.
It's really more convenient to just put on a hand-to-hand battery of variables:
$button-primary-normal-background: #0088cc;
$button-primary-normal-text:       #ffffff;
$button-primary-hover-background:  #0077b3;
$button-primary-hover-text:        #ffffff;
// ...

And in general, I could not find a situation where an array would be more convenient than just a set of variables. Although in theory it would be logical to use arrays to combine entities of the same type. Let's say for the same breakpoints in media queries.
It seems that the array will be more convenient only in a situation where the number of values ​​is not known in advance - in order to bypass them in a loop. And in the above example with buttons - nafig are not needed.
Perhaps I'm misunderstanding something and there are some good practices?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philip Gaponenko, 2018-02-14
@filgaponenko

It is good practice not to use all the features of the language (especially new ones) unnecessarily.
If a set of variables is enough, then you need to stop there, because your code will also need to be read by people, not just robots, so you should think about making a choice towards more maintainable code than towards more "optimized".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question