Skip to content

Commit

Permalink
Add a "subsequence?" helper to Util.
Browse files Browse the repository at this point in the history
  • Loading branch information
nex3 committed May 25, 2012
1 parent b2523c6 commit 29c7740
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/sass/util.rb
Expand Up @@ -253,6 +253,23 @@ def check_range(name, range, value, unit='')
"#{name} #{str} must be between #{range.first}#{unit} and #{range.last}#{unit}")
end

# Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether
# or not `seq2` contains every element in `seq1` in the same order (and
# possibly more elements besides).
#
# @param seq1 [Array]
# @param seq2 [Array]
# @return [Boolean]
def subsequence?(seq1, seq2)
i = j = 0
loop do
return true if i == seq1.size
return false if j == seq2.size
i += 1 if seq1[i] == seq2[j]
j += 1
end
end

# Returns information about the caller of the previous method.
#
# @param entry [String] An entry in the `#caller` list, or a similarly formatted string
Expand Down
10 changes: 10 additions & 0 deletions test/sass/util_test.rb
Expand Up @@ -120,6 +120,16 @@ def test_lcs_with_block
lcs([-5, 3, 2, 8], [-4, 1, 8]) {|a, b| (a - b).abs <= 1 && [a, b].max})
end

def test_subsequence
assert(subsequence?([1, 2, 3], [1, 2, 3]))
assert(subsequence?([1, 2, 3], [1, :a, 2, :b, 3]))
assert(subsequence?([1, 2, 3], [:a, 1, :b, :c, 2, :d, 3, :e, :f]))

assert(!subsequence?([1, 2, 3], [1, 2]))
assert(!subsequence?([1, 2, 3], [1, 3, 2]))
assert(!subsequence?([1, 2, 3], [3, 2, 1]))
end

def test_silence_warnings
old_stderr, $stderr = $stderr, StringIO.new
warn "Out"
Expand Down

0 comments on commit 29c7740

Please sign in to comment.