Skip to content

Instantly share code, notes, and snippets.

@agorilla
Last active March 7, 2020 11:01
Show Gist options
  • Save agorilla/9df052eb1e15d8aea446 to your computer and use it in GitHub Desktop.
Save agorilla/9df052eb1e15d8aea446 to your computer and use it in GitHub Desktop.
Sass function map-get-next
/// Function to get next map item
/// returns next map item or fallback value if map, key or next item does not exist
///
/// @author Simon Koch
///
/// @access public
///
/// @param {Map} $map - Sass list map
/// @param {String} $key - List map key
/// @param {String} $fallback (false) - Fallback value if map, key or next item does not exist
///
/// @example scss - Usage
/// $map: (
/// a: 100px,
/// b: 200px
/// );
///
/// .foo {
/// width: map-get-next($map, a);
/// }
///
/// .bar {
/// width: map-get-next($map, b, auto);
/// }
///
/// @example css - CSS output
/// .foo {
/// width: 200px;
/// }
///
/// .bar {
/// width: auto;
/// }
@function map-get-next($map, $key, $fallback: false) {
// Check if map is valid
@if type_of($map) == map {
// Check if key exists in map
@if map_has_key($map, $key) {
// Init index counter variable
$i: 0;
// Init key index
$key-index: false;
// Traverse map for key
@each $map-key, $map-value in $map {
// Update index
$i: $i + 1;
// If map key found, set key index
@if $map-key == $key {
$key-index: $i;
}
// If next index return next value
@if $i == $key-index + 1 {
@return $map-value;
}
// If last entry return false
@if $i == length($map) {
@return $fallback;
}
}
@warn 'No next map item for key #{$key}';
@return $fallback;
}
@warn 'No valid key #{$key} in map';
@return $fallback;
}
@warn 'No valid map';
@return $fallback;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment