Skip to content

Instantly share code, notes, and snippets.

@tobystokes
Last active May 18, 2017 17:00
Show Gist options
  • Save tobystokes/c4b34ef09593b7bdc51433d6f16e8a62 to your computer and use it in GitHub Desktop.
Save tobystokes/c4b34ef09593b7bdc51433d6f16e8a62 to your computer and use it in GitHub Desktop.
Based on https://gist.github.com/agorilla/9df052eb1e15d8aea446 , refactored to do prev as well
/// 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, Toby Stokes
///
/// @access public
///
/// @param {Map} $map - Sass list map
/// @param {String} $key - List map key of the current item
/// @param {String} $fallback (false) - Fallback value if map, key or next item does not exist. If this is 'loop' then returns the first item in the list
/// @param {String} $return (value) - Specifies whether to return the key or the value
///
/// @example scss - Usage
/// $map: (
/// a: 100px,
/// b: 200px
/// c: 300px
/// );
///
/// map-get-next($map, a); // returns 200px
/// map-get-next($map, c, loop); // returns 100px
/// map-get-next($map, c, auto); // returns fallback of auto
/// map-get-next($map, b, false, key); // returns c
///
@function map-get-next($map, $key, $fallback: false, $return: value) {
$key-index: get-map-key($map, $key);
$next-index: $key-index + 1;
@if $next-index > length($map) {
@if $fallback = loop {
$next-index: 1;
} @else {
@warn 'No next map item for key #{$key}';
@return $fallback;
}
}
@return map-match($map, $key, $next-index, $return);
}
@function map-get-prev($map, $key, $fallback: false, $return: value) {
$key-index: get-map-key($map, $key);
$next-index: $key-index - 1;
@if $next-index <= 0 {
@if $fallback = loop {
$next-index: length($map);
} @else {
@warn 'No next map item for key #{$key}';
@return $fallback;
}
}
@return map-match($map, $key, $next-index, $return);
}
@function get-map-key($map, $key) {
// Check if map is valid
@if type-of($map) == map {
// Check if key exists in map
@if map-has-key($map, $key) {
@return index(map-keys($map), $key);
}
@warn 'No valid key #{$key} in map';
@return $fallback;
}
@warn 'No valid map';
@return $fallback;
}
@function map-match($map, $key, $next-index, $return: value) {
// Init index counter variable
$i: 0;
// Traverse map for key
@each $map-key, $map-value in $map {
$i: $i + 1;
// If next index return next value or key based on $return
@if $i == $next-index {
@if $return == key {
@return $map-key;
} @else {
@return $map-value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment