Skip to content

Instantly share code, notes, and snippets.

@KittyGiraudel
Created April 2, 2014 09:59
Show Gist options
  • Save KittyGiraudel/9931274 to your computer and use it in GitHub Desktop.
Save KittyGiraudel/9931274 to your computer and use it in GitHub Desktop.
Generated by SassMeister.com.
// ----
// Sass (v3.3.4)
// Compass (v1.0.0.alpha.18)
// ----
// [Helper]
// Cast a stringified number to an actual number
// ---
// @param [string] $input: stringified number to cast
// ---
// @return [number] | $input
@function try-cast($input) {
$index: index('0' '1' '2' '3' '4' '5' '6' '7' '8' '9', $input);
@if type-of($input) == 'number'
or type-of($index) != 'number' {
@return $input;
}
@return nth(0 1 2 3 4 5 6 7 8 9, $index);
}
// [Helper]
// Function splitting a string as a list based on a needle
// ---
// @param [string] $string: string to split
// @paral [string] $needle (.): separator
// ---
// @return [list]
@function str-split($string, $needle: '.') {
$result: ();
@while str-index($string, $needle) {
$index: str-index($string, $needle);
$result: append($result, try-cast(str-slice($string, 1, $index - 1)));
$string: str-slice($string, $index + str-length($needle));
}
@return append($result, try-cast($string));
}
// [Core]
// Function to access values in nested maps/lists
// ---
// @param [map] | [list] $map: map or list to parse
// @param [string] $string: accessor
// ---
// @return [literal]
@function map-deep-get($map, $string) {
@each $key in str-split($string) {
$map: if(type-of($key) == string, map-get($map, $key), nth($map, $key));
}
@return $map;
}
// [Alias]
// Alias for `map-deep-get` function
@function dot($map, $string) {
@return map-deep-get($map, $string);
}
// Sample map
$map: (
tags: (incididunt, amet, sunt, incididunt, in, cupidatat, tempor),
friends: (
(
id: 0,
name: Audrey Henson
),
(
id: 1,
name: Nichole Macdonald
),
(
id: 2,
name: Christina Finch
)
),
config: (
breakpoints: (
desktop: 1200,
tablet: 900,
modile: 600
)
)
);
dot-accessor {
/* Catching the `2`nd item from `friends` from `$map` */
$test: 'friends.2';
#{$test}: inspect(dot($map, $test));
/* Catching the `name` of the `1`st item from `friends` from `$map` */
$test: 'friends.1.name';
#{$test}: dot($map, $test);
/* Catching the `4`th from `tags` from `$map` */
$test: 'tags.4';
#{$test}: dot($map, $test);
/* Catching the `desktop` value from `breakpoints` from `config` */
$test: 'config.breakpoints.desktop';
#{$test}: dot($map, $test);
}
dot-accessor {
/* Catching the `2`nd item from `friends` from `$map` */
friends.2: (id: 1, name: Nichole Macdonald);
/* Catching the `name` of the `1`st item from `friends` from `$map` */
friends.1.name: Audrey Henson;
/* Catching the `4`th from `tags` from `$map` */
tags.4: incididunt;
/* Catching the `desktop` value from `breakpoints` from `config` */
config.breakpoints.desktop: 1200;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment