Skip to content

Instantly share code, notes, and snippets.

@lunelson
Created January 30, 2014 11:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lunelson/8706648 to your computer and use it in GitHub Desktop.
Save lunelson/8706648 to your computer and use it in GitHub Desktop.
Optimized `set-nth()` vs old `replace-nth()`
// ----
// 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');
}
/*
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