Created
January 30, 2014 11:20
-
-
Save lunelson/8706648 to your computer and use it in GitHub Desktop.
Optimized `set-nth()` vs old `replace-nth()`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---- | |
// libsass (v0.7.0) | |
// ---- | |
/* | |
comparison of old and new replace-nth / set-nth | |
*/ | |
// algorithm copied from early version of sassylists | |
@function replace-nth($list, $value, $index, $sep: 'comma') { | |
$output: (); | |
@for $i from 1 through length($list) { | |
@if $i == $index { $output: append($output, $value, $sep); } | |
@else { $output: append($output, nth($list, $i), $sep); } } | |
@return $output; | |
} | |
// rewritten algorithm; name and syntax changed to match sass 3.3's 'set-nth()' | |
// now compensates for sass 3.3 nth() function's changes | |
@function set-nth($list, $index, $value, $sep: 'comma') { | |
$length: length($list); $output: (); | |
@if $index > $length or $index <= 0 { @return $list; } | |
@if $index > 1 { @for $i from 1 through $index - 1 { $output: append($output, nth($list, $i), $sep); } } | |
$output: append($output, $value, $sep); | |
@if $length > 1 { @for $i from $index + 1 through $length { $output: append($output, nth($list, $i), $sep); } } | |
@return $output; | |
} | |
// testing | |
$mylist: 1 2 3 4 5 6 7; | |
.test { | |
out: replace-nth($mylist, 'yo', 7); | |
out: set-nth($mylist, 7, 'yo'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
comparison of old and new replace-nth / set-nth | |
*/ | |
.test { | |
out: 1, 2, 3, 4, 5, 6, 'yo'; | |
out: 1, 2, 3, 4, 5, 6, 'yo'; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment