-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path_map-get-prev.scss
126 lines (114 loc) · 3.58 KB
/
_map-get-prev.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/// Function to get previous map item
/// returns previous map item or fallback value if map, key or previous item does not exist
///
/// @author Simon Koch <[email protected]>
///
/// Licensed under the MIT license.
///
/// @access public
///
/// @param {Map} $map - Sass list map
/// @param {String} $key - List map key
/// @param {Boolean} $fallback (false) - Fallback value if map, key or previous item does not exist
/// @param {String} $return (value) - Return value or key of previous list item
/// @param {Boolean} $debug (false) - Debug option
///
/// @example scss - Usage
/// $map: (
/// s: 320px,
/// m: 768px,
/// );
///
/// .foo {
/// width: map-get-prev($map, m);
/// }
///
/// .bar {
/// width: map-get-prev($map, s, 240px);
/// }
///
/// @example css - CSS output
/// .foo {
/// width: 320px;
/// }
///
/// .bar {
/// width: 240px;
/// }
@function map-get-prev($map, $key, $fallback: false, $return: value, $debug: false) {
// Check if map is valid
@if type-of($map) == map {
@if $debug {
@debug 'Map exists #{$map}';
}
// Check if key exists in map
@if map-has-key($map, $key) {
@if $debug {
@debug 'Map has key #{$key}';
}
// Init index counter variable
$i: 1;
// Init key index
$key-index: false;
$previous-index: false;
// Traverse map for key
@each $map-key, $map-value in $map {
@if $debug {
@debug 'map-key: #{$map-key}, map-value: #{$map-value}, i: #{$i}';
}
// If map key found, set key index
@if $map-key == $key {
$key-index: $i;
@if $debug {
@debug 'found key-index: #{$key-index}';
}
}
// Update index
$i: $i + 1;
}
// If the key-index exists, iterate through the map again
@if $key-index != false {
$previous-index: $key-index - 1;
$i: 1;
// If the previous key is less than one, use the fallback
@if $previous-index < 1 {
@warn 'no previous item in map, returning fallback';
@return $fallback;
}
@else {
// Traverse map for key
@each $map-key, $map-value in $map {
@if $i == $previous-index {
@if $return == 'key' {
@if $debug {
@debug 'found! returning map-key: #{$map-key}';
}
@return $map-key;
}
@else {
@if $debug {
@debug 'found! returning map-value: #{$map-value}';
}
@return $map-value;
}
}
// Update index
$i: $i + 1;
}
}
}
@else {
@warn 'No previous map item for key #{$key}';
@return $fallback;
}
}
@else {
@warn 'No valid key #{$key} in map';
@return $fallback;
}
}
@else {
@warn 'No valid map';
@return $fallback;
}
}