mirror of
https://github.com/jashkenas/coffeescript.git
synced 2022-11-09 12:23:24 -05:00
most of the examples converted to symbology.
This commit is contained in:
parent
58a5d93214
commit
da6ea27454
13 changed files with 216 additions and 229 deletions
|
@ -2,15 +2,15 @@
|
||||||
# The implementation of binary search that is tested.
|
# The implementation of binary search that is tested.
|
||||||
|
|
||||||
# Return the index of an element in a sorted list. (or -1, if not present)
|
# Return the index of an element in a sorted list. (or -1, if not present)
|
||||||
index: (list, target) ->
|
index = (list, target) ->
|
||||||
[low, high]: [0, list.length]
|
[low, high] = [0, list.length]
|
||||||
while low < high
|
while low < high
|
||||||
mid: (low + high) >> 1
|
mid = (low + high) >> 1
|
||||||
val: list[mid]
|
val = list[mid]
|
||||||
return mid if val is target
|
return mid if val is target
|
||||||
if val < target then low: mid + 1 else high: mid
|
if val < target then low = mid + 1 else high = mid
|
||||||
return -1
|
return -1
|
||||||
|
|
||||||
puts 2 is index([10, 20, 30, 40, 50], 30)
|
puts 2 is index [10, 20, 30, 40, 50], 30
|
||||||
puts 4 is index([-97, 35, 67, 88, 1200], 1200)
|
puts 4 is index [-97, 35, 67, 88, 1200], 1200
|
||||||
puts 0 is index([0, 45, 70], 0)
|
puts 0 is index [0, 45, 70], 0
|
|
@ -1,11 +1,11 @@
|
||||||
# Beautiful Code, Chapter 3.
|
# Beautiful Code, Chapter 3.
|
||||||
# Produces the expected runtime of Quicksort, for every integer from 1 to N.
|
# Produces the expected runtime of Quicksort, for every integer from 1 to N.
|
||||||
|
|
||||||
runtime: (N) ->
|
runtime = (N) ->
|
||||||
[sum, t]: [0, 0]
|
[sum, t] = [0, 0]
|
||||||
for n in [1..N]
|
for n in [1..N]
|
||||||
sum += 2 * t
|
sum += 2 * t
|
||||||
t: n - 1 + sum / n
|
t = n - 1 + sum / n
|
||||||
t
|
t
|
||||||
|
|
||||||
puts runtime(3) is 2.6666666666666665
|
puts runtime(3) is 2.6666666666666665
|
||||||
|
|
|
@ -3,16 +3,16 @@
|
||||||
# '.', '^', '$', and '*'.
|
# '.', '^', '$', and '*'.
|
||||||
|
|
||||||
# Search for the regexp anywhere in the text.
|
# Search for the regexp anywhere in the text.
|
||||||
match: (regexp, text) ->
|
match = (regexp, text) ->
|
||||||
return match_here(regexp.slice(1), text) if regexp[0] is '^'
|
return match_here(regexp.slice(1), text) if regexp[0] is '^'
|
||||||
while text
|
while text
|
||||||
return true if match_here(regexp, text)
|
return true if match_here(regexp, text)
|
||||||
text: text.slice(1)
|
text = text.slice(1)
|
||||||
false
|
false
|
||||||
|
|
||||||
# Search for the regexp at the beginning of the text.
|
# Search for the regexp at the beginning of the text.
|
||||||
match_here: (regexp, text) ->
|
match_here = (regexp, text) ->
|
||||||
[cur, next]: [regexp[0], regexp[1]]
|
[cur, next] = [regexp[0], regexp[1]]
|
||||||
if regexp.length is 0 then return true
|
if regexp.length is 0 then return true
|
||||||
if next is '*' then return match_star(cur, regexp.slice(2), text)
|
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 cur is '$' and not next then return text.length is 0
|
||||||
|
@ -20,11 +20,11 @@ match_here: (regexp, text) ->
|
||||||
false
|
false
|
||||||
|
|
||||||
# Search for a kleene star match at the beginning of the text.
|
# Search for a kleene star match at the beginning of the text.
|
||||||
match_star: (c, regexp, text) ->
|
match_star = (c, regexp, text) ->
|
||||||
loop
|
loop
|
||||||
return true if match_here(regexp, text)
|
return true if match_here(regexp, text)
|
||||||
return false unless text and (text[0] is c or c is '.')
|
return false unless text and (text[0] is c or c is '.')
|
||||||
text: text.slice(1)
|
text = text.slice(1)
|
||||||
|
|
||||||
puts match("ex", "some text")
|
puts match("ex", "some text")
|
||||||
puts match("s..t", "spit")
|
puts match("s..t", "spit")
|
||||||
|
|
|
@ -6,8 +6,8 @@ get '/hello', ->
|
||||||
|
|
||||||
|
|
||||||
# Append.
|
# Append.
|
||||||
append: (location, data) ->
|
append = (location, data) ->
|
||||||
path: new Pathname location
|
path = new Pathname location
|
||||||
throw new Error("Location does not exist") unless path.exists()
|
throw new Error("Location does not exist") unless path.exists()
|
||||||
|
|
||||||
File.open path, 'a', (file) ->
|
File.open path, 'a', (file) ->
|
||||||
|
@ -17,23 +17,20 @@ append: (location, data) ->
|
||||||
|
|
||||||
|
|
||||||
# Rubinius' File.open implementation.
|
# Rubinius' File.open implementation.
|
||||||
File.open: (path, mode, block) ->
|
File.open = (path, mode, block) ->
|
||||||
io: new File path, mode
|
io = new File path, mode
|
||||||
|
|
||||||
return io unless block
|
return io unless block
|
||||||
|
|
||||||
try
|
try
|
||||||
block io
|
block io
|
||||||
finally
|
finally
|
||||||
try
|
io.close() unless io.closed()
|
||||||
io.close() unless io.closed()
|
|
||||||
catch error
|
|
||||||
# nothing, just swallow them.
|
|
||||||
|
|
||||||
|
|
||||||
# Write.
|
# Write.
|
||||||
write: (location, data) ->
|
write = (location, data) ->
|
||||||
path: new Pathname location
|
path = new Pathname location
|
||||||
raise "Location does not exist" unless path.exists()
|
raise "Location does not exist" unless path.exists()
|
||||||
|
|
||||||
File.open path, 'w', (file) ->
|
File.open path, 'w', (file) ->
|
||||||
|
@ -43,15 +40,15 @@ write: (location, data) ->
|
||||||
|
|
||||||
|
|
||||||
# Rails' respond_to.
|
# Rails' respond_to.
|
||||||
index: ->
|
index = ->
|
||||||
people: Person.find 'all'
|
people = Person.find 'all'
|
||||||
|
|
||||||
respond_to (format) ->
|
respond_to (format) ->
|
||||||
format.html()
|
format.html()
|
||||||
format.xml -> render { xml: people.xml() }
|
format.xml -> render xml: people.xml()
|
||||||
|
|
||||||
|
|
||||||
# Synchronization.
|
# Synchronization.
|
||||||
synchronize: (block) ->
|
synchronize = (block) ->
|
||||||
lock()
|
lock()
|
||||||
try block() finally unlock()
|
try block() finally unlock()
|
||||||
|
|
|
@ -1,39 +1,37 @@
|
||||||
# Functions:
|
# Functions:
|
||||||
square: (x) -> x * x
|
square = (x) -> x * x
|
||||||
|
|
||||||
sum: (x, y) -> x + y
|
sum = (x, y) -> x + y
|
||||||
|
|
||||||
odd: (x) -> x % 2 isnt 0
|
odd = (x) -> x % 2 isnt 0
|
||||||
|
|
||||||
even: (x) -> x % 2 is 0
|
even = (x) -> x % 2 is 0
|
||||||
|
|
||||||
run_loop: ->
|
run_loop = ->
|
||||||
fire_events((e) -> e.stopPropagation())
|
fire_events((e) -> e.stopPropagation())
|
||||||
listen()
|
listen()
|
||||||
wait()
|
wait()
|
||||||
|
|
||||||
# Objects:
|
# Objects:
|
||||||
dense_object_literal: {one: 1, two: 2, three: 3}
|
dense_object_literal = {one: 1, two: 2, three: 3}
|
||||||
|
|
||||||
spaced_out_multiline_object: {
|
spaced_out_multiline_object =
|
||||||
pi: 3.14159
|
pi: 3.14159
|
||||||
list: [1, 2, 3, 4]
|
list: [1, 2, 3, 4]
|
||||||
regex: /match[ing](every|thing|\/)/gi
|
regex: /match[ing](every|thing|\/)/gi
|
||||||
three: new Idea
|
three: new Idea
|
||||||
|
|
||||||
inner_obj: {
|
inner_obj:
|
||||||
freedom: -> _.freedom()
|
freedom: -> _.freedom()
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Arrays:
|
# Arrays:
|
||||||
stooges: [{moe: 45}, {curly: 43}, {larry: 46}]
|
stooges = [{moe: 45}, {curly: 43}, {larry: 46}]
|
||||||
|
|
||||||
exponents: [(x) -> x, (x) -> x * x, (x) -> x * x * x]
|
exponents = [((x) -> x), ((x) -> x * x), ((x) -> x * x * x)]
|
||||||
|
|
||||||
empty: []
|
empty = []
|
||||||
|
|
||||||
multiline: [
|
multiline = [
|
||||||
'line one'
|
'line one'
|
||||||
'line two'
|
'line two'
|
||||||
]
|
]
|
||||||
|
@ -47,14 +45,14 @@ else if submarine.sinking
|
||||||
else
|
else
|
||||||
run_away()
|
run_away()
|
||||||
|
|
||||||
eldest: if 25 > 21 then liz else marge
|
eldest = if 25 > 21 then liz else marge
|
||||||
|
|
||||||
decoration: medal_of_honor if war_hero
|
decoration = medal_of_honor if war_hero
|
||||||
|
|
||||||
go_to_sleep() unless coffee
|
go_to_sleep() unless coffee
|
||||||
|
|
||||||
# Returning early:
|
# Returning early:
|
||||||
race: ->
|
race = ->
|
||||||
run()
|
run()
|
||||||
walk()
|
walk()
|
||||||
crawl()
|
crawl()
|
||||||
|
@ -62,13 +60,13 @@ race: ->
|
||||||
race()
|
race()
|
||||||
|
|
||||||
# Conditional assignment:
|
# Conditional assignment:
|
||||||
good ||= evil
|
good = or evil
|
||||||
wine &&= cheese
|
wine = and cheese
|
||||||
|
|
||||||
# Nested property access and calls.
|
# Nested property access and calls.
|
||||||
((moon.turn(360))).shapes[3].move({x: 45, y: 30}).position['top'].offset('x')
|
((moon.turn(360))).shapes[3].move({x: 45, y: 30}).position['top'].offset('x')
|
||||||
|
|
||||||
a: b: c: 5
|
a = b = c = 5
|
||||||
|
|
||||||
# Embedded JavaScript.
|
# Embedded JavaScript.
|
||||||
callback(
|
callback(
|
||||||
|
@ -102,19 +100,19 @@ loop
|
||||||
!!true
|
!!true
|
||||||
|
|
||||||
# Lexical scoping.
|
# Lexical scoping.
|
||||||
v_1: 5
|
v_1 = 5
|
||||||
change_a_and_set_b: ->
|
change_a_and_set_b = ->
|
||||||
v_1: 10
|
v_1 = 10
|
||||||
v_2: 15
|
v_2 = 15
|
||||||
v_2: 20
|
v_2 = 20
|
||||||
|
|
||||||
# Array comprehensions.
|
# Array comprehensions.
|
||||||
supper: food.capitalize() for food in ['toast', 'cheese', 'wine']
|
supper = food.capitalize() for food in ['toast', 'cheese', 'wine']
|
||||||
|
|
||||||
drink(bottle) for bottle, i in ['soda', 'wine', 'lemonade'] when even(i)
|
drink bottle for bottle, i in ['soda', 'wine', 'lemonade'] when even i
|
||||||
|
|
||||||
# Switch statements ("else" serves as a default).
|
# Switch statements ("else" serves as a default).
|
||||||
activity: switch day
|
activity = switch day
|
||||||
when "Tuesday" then eat_breakfast()
|
when "Tuesday" then eat_breakfast()
|
||||||
when "Sunday" then go_to_church()
|
when "Sunday" then go_to_church()
|
||||||
when "Saturday" then go_to_the_park()
|
when "Saturday" then go_to_the_park()
|
||||||
|
@ -128,50 +126,46 @@ activity: switch day
|
||||||
else go_to_work()
|
else go_to_work()
|
||||||
|
|
||||||
# Semicolons can optionally be used instead of newlines.
|
# Semicolons can optionally be used instead of newlines.
|
||||||
wednesday: -> eat_breakfast(); go_to_work(); eat_dinner()
|
wednesday = -> eat_breakfast(); go_to_work(); eat_dinner()
|
||||||
|
|
||||||
# Array slice literals.
|
# Array slice literals.
|
||||||
zero_to_nine: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
zero_to_nine = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||||
three_to_six: zero_to_nine[3..6]
|
three_to_six = zero_to_nine[3..6]
|
||||||
|
|
||||||
# Multiline strings with inner quotes.
|
# Multiline strings with inner quotes.
|
||||||
story: "Lorem ipsum dolor \"sit\" amet, consectetuer adipiscing elit,
|
story = "Lorem ipsum dolor \"sit\" amet, consectetuer adipiscing elit,
|
||||||
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna
|
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna
|
||||||
aliquam erat volutpat. Ut wisi enim ad."
|
aliquam erat volutpat. Ut wisi enim ad."
|
||||||
|
|
||||||
# Inheritance and calling super.
|
# Inheritance and calling super.
|
||||||
class Animal
|
class Animal
|
||||||
|
constructor: (@name) ->
|
||||||
|
|
||||||
move: (meters) ->
|
move: (meters) ->
|
||||||
alert this.name + " moved " + meters + "m."
|
alert this.name + " moved " + meters + "m."
|
||||||
|
|
||||||
class Snake extends Animal
|
class Snake extends Animal
|
||||||
constructor: (name) ->
|
|
||||||
@name: name
|
|
||||||
|
|
||||||
move: ->
|
move: ->
|
||||||
alert 'Slithering...'
|
alert 'Slithering...'
|
||||||
super 5
|
super 5
|
||||||
|
|
||||||
class Horse extends Animal
|
class Horse extends Animal
|
||||||
constructor: (name) ->
|
|
||||||
@name: name
|
|
||||||
|
|
||||||
move: ->
|
move: ->
|
||||||
alert 'Galloping...'
|
alert 'Galloping...'
|
||||||
super 45
|
super 45
|
||||||
|
|
||||||
sam: new Snake "Sammy the Snake"
|
sam = new Snake "Sammy the Snake"
|
||||||
tom: new Horse "Tommy the Horse"
|
tom = new Horse "Tommy the Horse"
|
||||||
|
|
||||||
sam.move()
|
sam.move()
|
||||||
tom.move()
|
tom.move()
|
||||||
|
|
||||||
# Numbers.
|
# Numbers.
|
||||||
a_googol: 1e100
|
a_googol = 1e100
|
||||||
hex: 0xff0000
|
hex = 0xff0000
|
||||||
negative: -1.0
|
negative = -1.0
|
||||||
infinity: Infinity
|
infinity = Infinity
|
||||||
nan: NaN
|
nan = NaN
|
||||||
|
|
||||||
# Deleting.
|
# Deleting.
|
||||||
delete secret.identity
|
delete secret.identity
|
|
@ -1,25 +1,25 @@
|
||||||
# Uses a binary search algorithm to locate a value in the specified array.
|
# Uses a binary search algorithm to locate a value in the specified array.
|
||||||
binary_search: (items, value) ->
|
binary_search = (items, value) ->
|
||||||
|
|
||||||
start: 0
|
start = 0
|
||||||
stop: items.length - 1
|
stop = items.length - 1
|
||||||
pivot: Math.floor((start + stop) / 2)
|
pivot = Math.floor (start + stop) / 2
|
||||||
|
|
||||||
while items[pivot] isnt value and start < stop
|
while items[pivot] isnt value and start < stop
|
||||||
|
|
||||||
# Adjust the search area.
|
# Adjust the search area.
|
||||||
stop: pivot - 1 if value < items[pivot]
|
stop = pivot - 1 if value < items[pivot]
|
||||||
start: pivot + 1 if value > items[pivot]
|
start = pivot + 1 if value > items[pivot]
|
||||||
|
|
||||||
# Recalculate the pivot.
|
# Recalculate the pivot.
|
||||||
pivot: Math.floor((stop + start) / 2)
|
pivot = Math.floor (stop + start) / 2
|
||||||
|
|
||||||
# Make sure we've found the correct value.
|
# Make sure we've found the correct value.
|
||||||
if items[pivot] is value then pivot else -1
|
if items[pivot] is value then pivot else -1
|
||||||
|
|
||||||
|
|
||||||
# Test the function.
|
# Test the function.
|
||||||
puts(2 is binary_search([10, 20, 30, 40, 50], 30))
|
puts 2 is binary_search [10, 20, 30, 40, 50], 30
|
||||||
puts(4 is binary_search([-97, 35, 67, 88, 1200], 1200))
|
puts 4 is binary_search [-97, 35, 67, 88, 1200], 1200
|
||||||
puts(0 is binary_search([0, 45, 70], 0))
|
puts 0 is binary_search [0, 45, 70], 0
|
||||||
puts(-1 is binary_search([0, 45, 70], 10))
|
puts(-1 is binary_search [0, 45, 70], 10)
|
|
@ -1,11 +1,11 @@
|
||||||
# A bubble sort implementation, sorting the given array in-place.
|
# A bubble sort implementation, sorting the given array in-place.
|
||||||
bubble_sort: (list) ->
|
bubble_sort = (list) ->
|
||||||
for i in [0...list.length]
|
for i in [0...list.length]
|
||||||
for j in [0...list.length - i]
|
for j in [0...list.length - i]
|
||||||
[list[j], list[j+1]]: [list[j+1], list[j]] if list[j] > list[j+1]
|
[list[j], list[j+1]] = [list[j+1], list[j]] if list[j] > list[j+1]
|
||||||
list
|
list
|
||||||
|
|
||||||
|
|
||||||
# Test the function.
|
# Test the function.
|
||||||
puts(bubble_sort([3, 2, 1]).join(' ') is '1 2 3')
|
puts bubble_sort([3, 2, 1]).join(' ') is '1 2 3'
|
||||||
puts(bubble_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9')
|
puts bubble_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9'
|
|
@ -2,7 +2,7 @@
|
||||||
class LinkedList
|
class LinkedList
|
||||||
|
|
||||||
constructor: ->
|
constructor: ->
|
||||||
this._head: null # Pointer to the first item in the list.
|
this._head = null # Pointer to the first item in the list.
|
||||||
|
|
||||||
|
|
||||||
# Appends some data to the end of the list. This method traverses the existing
|
# Appends some data to the end of the list. This method traverses the existing
|
||||||
|
@ -10,13 +10,13 @@ class LinkedList
|
||||||
add: (data) ->
|
add: (data) ->
|
||||||
|
|
||||||
# Create a new node object to wrap the data.
|
# Create a new node object to wrap the data.
|
||||||
node: {data: data, next: null}
|
node = data: data, next: null
|
||||||
|
|
||||||
current: this._head ||= node
|
current = this._head = or node
|
||||||
|
|
||||||
if this._head isnt node
|
if this._head isnt node
|
||||||
current: current.next while current.next
|
(current = current.next) while current.next
|
||||||
current.next: node
|
current.next = node
|
||||||
|
|
||||||
this
|
this
|
||||||
|
|
||||||
|
@ -27,11 +27,11 @@ class LinkedList
|
||||||
# Check for out-of-bounds values.
|
# Check for out-of-bounds values.
|
||||||
return null if index < 0
|
return null if index < 0
|
||||||
|
|
||||||
current: this._head or null
|
current = this._head or null
|
||||||
i: -1
|
i = -1
|
||||||
|
|
||||||
# Advance through the list.
|
# Advance through the list.
|
||||||
current: current.next while current and index > (i += 1)
|
(current = current.next) while current and index > (i += 1)
|
||||||
|
|
||||||
# Return null if we've reached the end.
|
# Return null if we've reached the end.
|
||||||
current and current.data
|
current and current.data
|
||||||
|
@ -43,19 +43,19 @@ class LinkedList
|
||||||
# Check for out-of-bounds values.
|
# Check for out-of-bounds values.
|
||||||
return null if index < 0
|
return null if index < 0
|
||||||
|
|
||||||
current: this._head or null
|
current = this._head or null
|
||||||
i: -1
|
i = -1
|
||||||
|
|
||||||
# Special case: removing the first item.
|
# Special case: removing the first item.
|
||||||
if index is 0
|
if index is 0
|
||||||
this._head: current.next
|
this._head = current.next
|
||||||
else
|
else
|
||||||
|
|
||||||
# Find the right location.
|
# Find the right location.
|
||||||
[previous, current]: [current, current.next] while index > (i += 1)
|
([previous, current] = [current, current.next]) while index > (i += 1)
|
||||||
|
|
||||||
# Skip over the item to remove.
|
# Skip over the item to remove.
|
||||||
previous.next: current.next
|
previous.next = current.next
|
||||||
|
|
||||||
# Return the value.
|
# Return the value.
|
||||||
current and current.data
|
current and current.data
|
||||||
|
@ -63,24 +63,24 @@ class LinkedList
|
||||||
|
|
||||||
# Calculate the number of items in the list.
|
# Calculate the number of items in the list.
|
||||||
size: ->
|
size: ->
|
||||||
current: this._head
|
current = this._head
|
||||||
count: 0
|
count = 0
|
||||||
|
|
||||||
while current
|
while current
|
||||||
count += 1
|
count += 1
|
||||||
current: current.next
|
current = current.next
|
||||||
|
|
||||||
count
|
count
|
||||||
|
|
||||||
|
|
||||||
# Convert the list into an array.
|
# Convert the list into an array.
|
||||||
toArray: ->
|
toArray: ->
|
||||||
result: []
|
result = []
|
||||||
current: this._head
|
current = this._head
|
||||||
|
|
||||||
while current
|
while current
|
||||||
result.push(current.data)
|
result.push current.data
|
||||||
current: current.next
|
current = current.next
|
||||||
|
|
||||||
result
|
result
|
||||||
|
|
||||||
|
@ -90,19 +90,19 @@ class LinkedList
|
||||||
|
|
||||||
|
|
||||||
# Tests.
|
# Tests.
|
||||||
list: new LinkedList
|
list = new LinkedList
|
||||||
|
|
||||||
list.add("Hi")
|
list.add("Hi")
|
||||||
puts(list.size() is 1)
|
puts list.size() is 1
|
||||||
puts(list.item(0) is "Hi")
|
puts list.item(0) is "Hi"
|
||||||
puts(list.item(1) is null)
|
puts list.item(1) is null
|
||||||
|
|
||||||
list: new LinkedList
|
list = new LinkedList
|
||||||
list.add("zero").add("one").add("two")
|
list.add("zero").add("one").add("two")
|
||||||
puts(list.size() is 3)
|
puts list.size() is 3
|
||||||
puts(list.item(2) is "two")
|
puts list.item(2) is "two"
|
||||||
puts(list.remove(1) is "one")
|
puts list.remove(1) is "one"
|
||||||
puts(list.item(0) is "zero")
|
puts list.item(0) is "zero"
|
||||||
puts(list.item(1) is "two")
|
puts list.item(1) is "two"
|
||||||
puts(list.size() is 2)
|
puts list.size() is 2
|
||||||
puts(list.item(-10) is null)
|
puts list.item(-10) is null
|
||||||
|
|
|
@ -2,15 +2,15 @@
|
||||||
# numbers, national insurance numbers, etc.
|
# numbers, national insurance numbers, etc.
|
||||||
# See: http://en.wikipedia.org/wiki/Luhn_algorithm
|
# See: http://en.wikipedia.org/wiki/Luhn_algorithm
|
||||||
|
|
||||||
is_valid_identifier: (identifier) ->
|
is_valid_identifier = (identifier) ->
|
||||||
|
|
||||||
sum: 0
|
sum = 0
|
||||||
alt: false
|
alt = false
|
||||||
|
|
||||||
for i in [(identifier.length - 1)..0]
|
for i in [(identifier.length - 1)..0]
|
||||||
|
|
||||||
# Get the next digit.
|
# Get the next digit.
|
||||||
num: parseInt(identifier.charAt(i), 10)
|
num = parseInt identifier.charAt(i), 10
|
||||||
|
|
||||||
# If it's not a valid number, abort.
|
# If it's not a valid number, abort.
|
||||||
return false if isNaN(num)
|
return false if isNaN(num)
|
||||||
|
@ -18,10 +18,10 @@ is_valid_identifier: (identifier) ->
|
||||||
# If it's an alternate number...
|
# If it's an alternate number...
|
||||||
if alt
|
if alt
|
||||||
num *= 2
|
num *= 2
|
||||||
num: (num % 10) + 1 if num > 9
|
num = (num % 10) + 1 if num > 9
|
||||||
|
|
||||||
# Flip the alternate bit.
|
# Flip the alternate bit.
|
||||||
alt: !alt
|
alt = !alt
|
||||||
|
|
||||||
# Add to the rest of the sum.
|
# Add to the rest of the sum.
|
||||||
sum += num
|
sum += num
|
||||||
|
@ -31,6 +31,6 @@ is_valid_identifier: (identifier) ->
|
||||||
|
|
||||||
|
|
||||||
# Tests.
|
# Tests.
|
||||||
puts(is_valid_identifier("49927398716") is true)
|
puts is_valid_identifier("49927398716") is true
|
||||||
puts(is_valid_identifier("4408041234567893") is true)
|
puts is_valid_identifier("4408041234567893") is true
|
||||||
puts(is_valid_identifier("4408041234567890") is false)
|
puts is_valid_identifier("4408041234567890") is false
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
# Sorts an array in ascending natural order using merge sort.
|
# Sorts an array in ascending natural order using merge sort.
|
||||||
merge_sort: (list) ->
|
merge_sort = (list) ->
|
||||||
|
|
||||||
return list if list.length is 1
|
return list if list.length is 1
|
||||||
|
|
||||||
result: []
|
result = []
|
||||||
pivot: Math.floor(list.length / 2)
|
pivot = Math.floor list.length / 2
|
||||||
left: merge_sort(list.slice(0, pivot))
|
left = merge_sort list.slice 0, pivot
|
||||||
right: merge_sort(list.slice(pivot))
|
right = merge_sort list.slice pivot
|
||||||
|
|
||||||
while left.length and right.length
|
while left.length and right.length
|
||||||
result.push(if left[0] < right[0] then left.shift() else right.shift())
|
result.push(if left[0] < right[0] then left.shift() else right.shift())
|
||||||
|
@ -15,5 +15,5 @@ merge_sort: (list) ->
|
||||||
|
|
||||||
|
|
||||||
# Test the function.
|
# Test the function.
|
||||||
puts(merge_sort([3, 2, 1]).join(' ') is '1 2 3')
|
puts merge_sort([3, 2, 1]).join(' ') is '1 2 3'
|
||||||
puts(merge_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9')
|
puts merge_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9'
|
|
@ -1,23 +1,23 @@
|
||||||
# An in-place selection sort.
|
# An in-place selection sort.
|
||||||
selection_sort: (list) ->
|
selection_sort = (list) ->
|
||||||
len: list.length
|
len = list.length
|
||||||
|
|
||||||
# For each item in the list.
|
# For each item in the list.
|
||||||
for i in [0...len]
|
for i in [0...len]
|
||||||
|
|
||||||
# Set the minimum to this position.
|
# Set the minimum to this position.
|
||||||
min: i
|
min = i
|
||||||
|
|
||||||
# Check the rest of the array to see if anything is smaller.
|
# Check the rest of the array to see if anything is smaller.
|
||||||
(min: j if list[j] < list[min]) for j in [(i+1)...len]
|
(min = j if list[j] < list[min]) for j in [(i+1)...len]
|
||||||
|
|
||||||
# Swap if a smaller item has been found.
|
# Swap if a smaller item has been found.
|
||||||
[list[i], list[min]]: [list[min], list[i]] if i isnt min
|
[list[i], list[min]] = [list[min], list[i]] if i isnt min
|
||||||
|
|
||||||
# The list is now sorted.
|
# The list is now sorted.
|
||||||
list
|
list
|
||||||
|
|
||||||
|
|
||||||
# Test the function.
|
# Test the function.
|
||||||
puts(selection_sort([3, 2, 1]).join(' ') is '1 2 3')
|
puts selection_sort([3, 2, 1]).join(' ') is '1 2 3'
|
||||||
puts(selection_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9')
|
puts selection_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9'
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
# ['toast', 'cheese', 'wine'].each { |food| print food.capitalize }
|
# ['toast', 'cheese', 'wine'].each { |food| print food.capitalize }
|
||||||
|
|
||||||
['toast', 'wine', 'cheese'].each (food) -> print(food.capitalize())
|
['toast', 'wine', 'cheese'].each (food) -> print food.capitalize()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -13,12 +13,11 @@
|
||||||
# def purchased=(var); @purchased = var; end
|
# def purchased=(var); @purchased = var; end
|
||||||
# end
|
# end
|
||||||
|
|
||||||
LotteryTicket: {
|
LotteryTicket =
|
||||||
get_picks: -> this.picks
|
get_picks: -> @picks
|
||||||
set_picks: (nums) -> this.picks: nums
|
set_picks: (@picks) ->
|
||||||
get_purchase: -> this.purchase
|
get_purchased: -> @purchase
|
||||||
set_purchase: (amount) -> this.purchase: amount
|
set_purchased: (@purchased) ->
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -39,19 +38,18 @@ LotteryTicket: {
|
||||||
# end
|
# end
|
||||||
# end
|
# end
|
||||||
|
|
||||||
LotteryDraw: {
|
LotteryDraw =
|
||||||
play: ->
|
play: ->
|
||||||
result: LotteryTicket.new_random()
|
result = LotteryTicket.new_random()
|
||||||
winners: {}
|
winners = {}
|
||||||
this.tickets.each (buyer, ticket_list) ->
|
this.tickets.each (buyer, ticket_list) ->
|
||||||
ticket_list.each (ticket) ->
|
ticket_list.each (ticket) ->
|
||||||
score: ticket.score(result)
|
score = ticket.score result
|
||||||
return if score is 0
|
return if score is 0
|
||||||
winners[buyer] ||= []
|
winners[buyer] = or []
|
||||||
winners[buyer].push([ticket, score])
|
winners[buyer].push [ticket, score]
|
||||||
this.tickets: {}
|
this.tickets = {}
|
||||||
winners
|
winners
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -64,11 +62,10 @@ LotteryDraw: {
|
||||||
# end
|
# end
|
||||||
# end
|
# end
|
||||||
|
|
||||||
WishScanner: {
|
WishScanner =
|
||||||
scan_for_a_wish: ->
|
scan_for_a_wish: ->
|
||||||
wish: this.read().detect((thought) -> thought.index('wish: ') is 0)
|
wish = this.read().detect (thought) -> thought.index('wish: ') is 0
|
||||||
wish.replace('wish: ', '')
|
wish.replace 'wish: ', ''
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -108,34 +105,32 @@ WishScanner: {
|
||||||
#
|
#
|
||||||
# end
|
# end
|
||||||
|
|
||||||
Creature : {
|
Creature =
|
||||||
|
|
||||||
# This method applies a hit taken during a fight.
|
# This method applies a hit taken during a fight.
|
||||||
hit: (damage) ->
|
hit: (damage) ->
|
||||||
p_up: Math.rand(this.charisma)
|
p_up = Math.rand this.charisma
|
||||||
if p_up % 9 is 7
|
if p_up % 9 is 7
|
||||||
this.life += p_up / 4
|
this.life += p_up / 4
|
||||||
puts("[" + this.name + " magick powers up " + p_up + "!]")
|
puts "[" + this.name + " magick powers up " + p_up + "!]"
|
||||||
this.life -= damage
|
this.life -= damage
|
||||||
if this.life <= 0 then puts("[" + this.name + " has died.]")
|
if this.life <= 0 then puts "[" + this.name + " has died.]"
|
||||||
|
|
||||||
# This method takes one turn in a fight.
|
# This method takes one turn in a fight.
|
||||||
fight: (enemy, weapon) ->
|
fight: (enemy, weapon) ->
|
||||||
if this.life <= 0 then return puts("[" + this.name + "is too dead to fight!]")
|
if this.life <= 0 then return puts "[" + this.name + "is too dead to fight!]"
|
||||||
|
|
||||||
# Attack the opponent.
|
# Attack the opponent.
|
||||||
your_hit: Math.rand(this.strength + weapon)
|
your_hit = Math.rand this.strength + weapon
|
||||||
puts("[You hit with " + your_hit + "points of damage!]")
|
puts "[You hit with " + your_hit + "points of damage!]"
|
||||||
enemy.hit(your_hit)
|
enemy.hit your_hit
|
||||||
|
|
||||||
# Retaliation.
|
# Retaliation.
|
||||||
puts(enemy)
|
puts enemy
|
||||||
if enemy.life > 0
|
if enemy.life > 0
|
||||||
enemy_hit: Math.rand(enemy.strength + enemy.weapon)
|
enemy_hit = Math.rand enemy.strength + enemy.weapon
|
||||||
puts("[Your enemy hit with " + enemy_hit + "points of damage!]")
|
puts "[Your enemy hit with " + enemy_hit + "points of damage!]"
|
||||||
this.hit(enemy_hit)
|
this.hit enemy_hit
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -154,14 +149,14 @@ Creature : {
|
||||||
# end
|
# end
|
||||||
|
|
||||||
# Get evil idea and swap in code words
|
# Get evil idea and swap in code words
|
||||||
print("Enter your new idea: ")
|
print "Enter your new idea: "
|
||||||
idea: gets()
|
idea = gets()
|
||||||
code_words.each((real, code) -> idea.replace(real, code))
|
code_words.each (real, code) -> idea.replace(real, code)
|
||||||
|
|
||||||
# Save the jibberish to a new file
|
# Save the jibberish to a new file
|
||||||
print("File encoded. Please enter a name for this idea: ")
|
print "File encoded. Please enter a name for this idea: "
|
||||||
idea_name: gets().strip()
|
idea_name = gets().strip()
|
||||||
File.open("idea-" + idea_name + '.txt', 'w', (file) -> file.write(idea))
|
File.open "idea-" + idea_name + '.txt', 'w', (file) -> file.write idea
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -177,10 +172,10 @@ File.open("idea-" + idea_name + '.txt', 'w', (file) -> file.write(idea))
|
||||||
# end
|
# end
|
||||||
# end
|
# end
|
||||||
|
|
||||||
wipe_mutterings_from: (sentence) ->
|
wipe_mutterings_from = (sentence) ->
|
||||||
throw new Error("cannot wipe mutterings") unless sentence.indexOf
|
throw new Error "cannot wipe mutterings" unless sentence.indexOf
|
||||||
while sentence.indexOf('(') >= 0
|
while sentence.indexOf('(') >= 0
|
||||||
open: sentence.indexOf('(') - 1
|
open = sentence.indexOf('(') - 1
|
||||||
close: sentence.indexOf(')') + 1
|
close = sentence.indexOf(')') + 1
|
||||||
sentence: sentence[0..open] + sentence[close..sentence.length]
|
sentence = sentence[0..open] + sentence[close..sentence.length]
|
||||||
sentence
|
sentence
|
|
@ -2,14 +2,14 @@
|
||||||
|
|
||||||
# 5 times: "Odelay!" print.
|
# 5 times: "Odelay!" print.
|
||||||
|
|
||||||
print("Odelay!") for i in [1..5]
|
print "Odelay!" for [1..5]
|
||||||
|
|
||||||
|
|
||||||
# add = (x, y): x + y.
|
# add = (x, y): x + y.
|
||||||
# add(2, 4) string print
|
# add(2, 4) string print
|
||||||
|
|
||||||
add: (x, y) -> x + y
|
add = (x, y) -> x + y
|
||||||
print(add(2, 4))
|
print add 2, 4
|
||||||
|
|
||||||
|
|
||||||
# loop: 'quaff' print.
|
# loop: 'quaff' print.
|
||||||
|
@ -19,25 +19,25 @@ loop print 'quaff'
|
||||||
|
|
||||||
# ('cheese', 'bread', 'mayo') at (1) print
|
# ('cheese', 'bread', 'mayo') at (1) print
|
||||||
|
|
||||||
print(['cheese', 'bread', 'mayo'][1])
|
print ['cheese', 'bread', 'mayo'][1]
|
||||||
|
|
||||||
|
|
||||||
# (language='Potion', pointless=true) at (key='language') print
|
# (language='Potion', pointless=true) at (key='language') print
|
||||||
|
|
||||||
print({language: 'Potion', pointless: true}['language'])
|
print {language: 'Potion', pointless: true}['language']
|
||||||
|
|
||||||
|
|
||||||
# minus = (x, y): x - y.
|
# minus = (x, y): x - y.
|
||||||
# minus (y=10, x=6)
|
# minus (y=10, x=6)
|
||||||
|
|
||||||
minus: (x, y) -> x - y
|
minus = (x, y) -> x - y
|
||||||
minus(6, 10)
|
minus 6, 10
|
||||||
|
|
||||||
|
|
||||||
# foods = ('cheese', 'bread', 'mayo')
|
# foods = ('cheese', 'bread', 'mayo')
|
||||||
# foods (2)
|
# foods (2)
|
||||||
|
|
||||||
foods: ['cheese', 'bread', 'mayo']
|
foods = ['cheese', 'bread', 'mayo']
|
||||||
foods[2]
|
foods[2]
|
||||||
|
|
||||||
|
|
||||||
|
@ -45,7 +45,7 @@ foods[2]
|
||||||
# (key, ' is a ', val) join print.
|
# (key, ' is a ', val) join print.
|
||||||
|
|
||||||
for key, val of {dog: 'canine', cat: 'feline', fox: 'vulpine'}
|
for key, val of {dog: 'canine', cat: 'feline', fox: 'vulpine'}
|
||||||
print(key + ' is a ' + val)
|
print key + ' is a ' + val
|
||||||
|
|
||||||
|
|
||||||
# Person = class: /name, /age, /sex.
|
# Person = class: /name, /age, /sex.
|
||||||
|
@ -54,13 +54,13 @@ for key, val of {dog: 'canine', cat: 'feline', fox: 'vulpine'}
|
||||||
|
|
||||||
class Person
|
class Person
|
||||||
print: ->
|
print: ->
|
||||||
print 'My name is ' + this.name + '.'
|
print 'My name is ' + @name + '.'
|
||||||
|
|
||||||
|
|
||||||
# p = Person ()
|
# p = Person ()
|
||||||
# p /name string print
|
# p /name string print
|
||||||
|
|
||||||
p: new Person
|
p = new Person
|
||||||
print p.name
|
print p.name
|
||||||
|
|
||||||
|
|
||||||
|
@ -71,10 +71,10 @@ print p.name
|
||||||
# Policeman ('Constable') print
|
# Policeman ('Constable') print
|
||||||
|
|
||||||
class Policeman extends Person
|
class Policeman extends Person
|
||||||
constructor: (rank) ->
|
constructor: (@rank) ->
|
||||||
@rank: rank
|
|
||||||
print: ->
|
print: ->
|
||||||
print 'My name is ' + this.name + " and I'm a " + this.rank + '.'
|
print 'My name is ' + @name + " and I'm a " + @rank + '.'
|
||||||
|
|
||||||
print new Policeman 'Constable'
|
print new Policeman 'Constable'
|
||||||
|
|
||||||
|
@ -83,11 +83,13 @@ print new Policeman 'Constable'
|
||||||
# [para 'Welcome.', button 'OK']]
|
# [para 'Welcome.', button 'OK']]
|
||||||
# app first name
|
# app first name
|
||||||
|
|
||||||
app = {
|
app =
|
||||||
window: {width: 200, height: 200}
|
window:
|
||||||
|
width: 200
|
||||||
|
height: 200
|
||||||
para: 'Welcome.'
|
para: 'Welcome.'
|
||||||
button: 'OK'
|
button: 'OK'
|
||||||
}
|
|
||||||
app.window
|
app.window
|
||||||
|
|
||||||
|
|
||||||
|
@ -96,33 +98,32 @@ app.window
|
||||||
#
|
#
|
||||||
# x = 1, y = 2
|
# x = 1, y = 2
|
||||||
|
|
||||||
x: 1
|
x = 1
|
||||||
y: 2
|
y = 2
|
||||||
|
|
||||||
x: 1; y: 2
|
x = 1; y = 2
|
||||||
|
|
||||||
|
|
||||||
# table = (language='Potion'
|
# table = (language='Potion'
|
||||||
# pointless=true)
|
# pointless=true)
|
||||||
|
|
||||||
table: {
|
table =
|
||||||
language: 'Potion'
|
language: 'Potion'
|
||||||
pointless: yes
|
pointless: yes
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# # this foul business...
|
# # this foul business...
|
||||||
# String length = (): 10.
|
# String length = (): 10.
|
||||||
|
|
||||||
# this foul business...
|
# this foul business...
|
||||||
String::length: -> 10
|
String::length = -> 10
|
||||||
|
|
||||||
|
|
||||||
# block = :
|
# block = :
|
||||||
# 'potion' print.
|
# 'potion' print.
|
||||||
|
|
||||||
block: ->
|
block = ->
|
||||||
print('potion')
|
print 'potion'
|
||||||
|
|
||||||
|
|
||||||
# if (age > 100): 'ancient'.
|
# if (age > 100): 'ancient'.
|
||||||
|
@ -156,30 +157,30 @@ switch author
|
||||||
# 'quaff' print
|
# 'quaff' print
|
||||||
# count--.
|
# count--.
|
||||||
|
|
||||||
count: 8
|
count = 8
|
||||||
while count > 0
|
while count > 0
|
||||||
print('quaff')
|
print 'quaff'
|
||||||
count--
|
count--
|
||||||
|
|
||||||
|
|
||||||
# 1 to 5 (a):
|
# 1 to 5 (a):
|
||||||
# a string print.
|
# a string print.
|
||||||
|
|
||||||
print(a) for a in [1..5]
|
print a for a in [1..5]
|
||||||
|
|
||||||
|
|
||||||
# if (3 ?gender):
|
# if (3 ?gender):
|
||||||
# "Huh? Numbers are sexed? That's amazing." print.
|
# "Huh? Numbers are sexed? That's amazing." print.
|
||||||
|
|
||||||
if (3).gender?
|
if (3).gender?
|
||||||
print("Huh? Numbers are sexed? That's amazing.")
|
print "Huh? Numbers are sexed? That's amazing."
|
||||||
|
|
||||||
|
|
||||||
# HomePage get = (url):
|
# HomePage get = (url):
|
||||||
# session = url query ? at ('session').
|
# session = url query ? at ('session').
|
||||||
|
|
||||||
HomePage::get: (url) ->
|
HomePage::get = (url) ->
|
||||||
session: url.query.session if url.query?
|
session = url.query.session if url.query?
|
||||||
|
|
||||||
|
|
||||||
# BTree = class: /left, /right.
|
# BTree = class: /left, /right.
|
||||||
|
@ -187,10 +188,10 @@ HomePage::get: (url) ->
|
||||||
# b /left = BTree ()
|
# b /left = BTree ()
|
||||||
# b /right = BTree ()
|
# b /right = BTree ()
|
||||||
|
|
||||||
BTree: ->
|
BTree = ->
|
||||||
b: new BTree
|
b = new BTree
|
||||||
b.left: new BTree
|
b.left = new BTree
|
||||||
b.right: new BTree
|
b.right = new BTree
|
||||||
|
|
||||||
|
|
||||||
# BTree = class: /left, /right.
|
# BTree = class: /left, /right.
|
||||||
|
@ -199,7 +200,7 @@ b.right: new BTree
|
||||||
# if (b ? /left):
|
# if (b ? /left):
|
||||||
# 'left path found!' print.
|
# 'left path found!' print.
|
||||||
|
|
||||||
BTree: ->
|
BTree = ->
|
||||||
b: new BTree
|
b = new BTree
|
||||||
|
|
||||||
print('left path found!') if b.left?
|
print 'left path found!' if b.left?
|
||||||
|
|
Loading…
Add table
Reference in a new issue