Skip to content

Commit

Permalink
Add an nth function.
Browse files Browse the repository at this point in the history
  • Loading branch information
nex3 committed Nov 10, 2010
1 parent 66ca14c commit d13cb92
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/sass/script/functions.rb
Expand Up @@ -969,6 +969,29 @@ def length(list)
end
declare :length, [:list]

# Gets the nth item in a list.
#
# Note that unlike some languages, the first item in a Sass list is number 1,
# the second number 2, and so forth.
#
# @param list [Literal] The list
# @param n [Number] The index into the list
# @return [Literal] The nth item in the list
# @raise [ArgumentError] If `n` isn't an integer between 1 and the list's length.
def nth(list, n)
assert_type n, :Number
if !n.int?
raise ArgumentError.new("List index #{n} must be an integer")
elsif n.to_i < 1
raise ArgumentError.new("List index #{n} must be greater than or equal to 1")
elsif n.to_i > (size = list.to_a.size)
raise ArgumentError.new("List index is #{n} but list is only #{size} item#{'s' if size != 1} long")
end

list.to_a[n.to_i - 1]
end
declare :nth, [:list, :n]

private

# This method implements the pattern of transforming a numeric value into
Expand Down
13 changes: 13 additions & 0 deletions test/sass/functions_test.rb
Expand Up @@ -607,6 +607,19 @@ def test_length
assert_equal("1", evaluate("length(#f00)"))
end

def test_nth
assert_equal("1", evaluate("nth(1 2 3, 1)"))
assert_equal("2", evaluate("nth(1 2 3, 2)"))
assert_equal("3", evaluate("nth((1, 2, 3), 3)"))
assert_equal("foo", evaluate("nth(foo, 1)"))
assert_equal("bar baz", evaluate("nth(foo (bar baz) bang, 2)"))
assert_error_message("List index 0 must be greater than or equal to 1 for `nth'", "nth(foo, 0)")
assert_error_message("List index -10 must be greater than or equal to 1 for `nth'", "nth(foo, -10)")
assert_error_message("List index 1.5 must be an integer for `nth'", "nth(foo, 1.5)")
assert_error_message("List index is 5 but list is only 4 items long for `nth'", "nth(1 2 3 4, 5)")
assert_error_message("List index is 2 but list is only 1 item long for `nth'", "nth(foo, 2)")
end

def test_keyword_args_rgb
assert_equal(%Q{white}, evaluate("rgb($red: 255, $green: 255, $blue: 255)"))
end
Expand Down

0 comments on commit d13cb92

Please sign in to comment.