mirror of
https://github.com/jashkenas/coffeescript.git
synced 2022-11-09 12:23:24 -05:00
added the first chapter of beautiful code as a coffeescript example
This commit is contained in:
parent
2d90a751f7
commit
4609ad78c2
2 changed files with 42 additions and 4 deletions
34
examples/beautiful_code/regular_expression_matcher.coffee
Normal file
34
examples/beautiful_code/regular_expression_matcher.coffee
Normal file
|
@ -0,0 +1,34 @@
|
|||
# Beautiful Code, chapter 1.
|
||||
# Implements a regular expression matcher that supports characters,
|
||||
# '.', '^', '$', and '*'.
|
||||
|
||||
# Search for the regexp anywhere in the text.
|
||||
match: regexp, text =>
|
||||
return match_here(regexp.slice(1), text) if regexp[0] is '^'
|
||||
while text
|
||||
return true if match_here(regexp, text)
|
||||
text: text.slice(1)
|
||||
false
|
||||
|
||||
# Search for the regexp at the beginning of the text.
|
||||
match_here: regexp, text =>
|
||||
[cur, next]: [regexp[0], regexp[1]]
|
||||
if regexp.length is 0 then return true
|
||||
if next is '*' then return match_star(cur, regexp.slice(2), text)
|
||||
if cur is '$' and not next then return text.length is 0
|
||||
if text and (cur is '.' or cur is text[0]) then return match_here(regexp.slice(1), text.slice(1))
|
||||
false
|
||||
|
||||
# Search for a kleene star match at the beginning of the text.
|
||||
match_star: c, regexp, text =>
|
||||
while true
|
||||
return true if match_here(regexp, text)
|
||||
return false unless text and (text[0] is c or c is '.')
|
||||
text: text.slice(1)
|
||||
|
||||
print(match("ex", "some text"))
|
||||
print(match("s..t", "spit"))
|
||||
print(match("^..t", "buttercup"))
|
||||
print(match("i..$", "cherries"))
|
||||
print(match("o*m", "vrooooommm!"))
|
||||
print(match("^hel*o$", "hellllllo"))
|
|
@ -4,12 +4,16 @@ class ExecutionTest < Test::Unit::TestCase
|
|||
|
||||
NO_WARNINGS = "0 error(s), 0 warning(s)"
|
||||
|
||||
SOURCES = [
|
||||
'test/fixtures/execution/*.coffee',
|
||||
'examples/beautiful_code/*.coffee'
|
||||
]
|
||||
|
||||
# This is by far the most important test. It evaluates all of the
|
||||
# CoffeeScript in test/fixtures/execution, ensuring that all our
|
||||
# syntax actually works.
|
||||
# CoffeeScript in test/fixtures/execution, as well as examples/beautiful_code,
|
||||
# ensuring that all our syntax actually works.
|
||||
def test_execution_of_coffeescript
|
||||
sources = ['test/fixtures/execution/*.coffee'].join(' ')
|
||||
(`bin/coffee -r #{sources}`).split("\n").each do |line|
|
||||
(`bin/coffee -r #{SOURCES.join(' ')}`).split("\n").each do |line|
|
||||
assert line == "true"
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue