A Map Function for Sass

May 9, 2015 at 3:27PM

Sass doesn't have a built in map function for lists and furthermore online searches on the subject will yield you tons of information about Sass maps... and next to nothing about how to make a map function in Sass1.

So here a basic implementation2 I worked out for a simple map function in Sass3:

@function map_function($list, $function_name)
  $return_list: ()

  @for $index from 1 through length($list)
    $call_result: call($function_name, nth($list, $index))
    $return_list: append($return_list, $call_result)

  @return $return_list

And for those of you who like all those extra curly brackets, the SCSS equivalent is:

@function map_function($list, $function_name) {
  $return_list: ();
  @for $index from 1 through length($list) {
    $call_result: call($function_name, nth($list, $index));
    $return_list: append($return_list, $call_result);
  }
  @return $return_list;
}
  1. Luckily however Sass has excellent documentation, so when search fails, that's a great place to start.
  2. Since you can't pass functions as parameters in Sass; in my implementation I use call to accomplish the same effect. The downside is that the function name has to be passed to the final map_function quoted.
  3. A map function, given a list and a function name, returns a new list containing the function called against each entry. For primer on what a map function is.. further than this baseline explanation, refer here.