Skip to content

Commit

Permalink
Back to non-naked constructor, @, preincrement, comprehension bracket…
Browse files Browse the repository at this point in the history
…ing, idioms: calls, comprehensions, interpolations
  • Loading branch information
xixixao committed Dec 9, 2013
1 parent 8cd9ba1 commit b859d92
Show file tree
Hide file tree
Showing 10 changed files with 65 additions and 66 deletions.
2 changes: 1 addition & 1 deletion examples/blocks.coffee
Expand Up @@ -31,7 +31,7 @@ File.open = (path, mode, block) ->
# Write.
write = (location, data) ->
path = new Pathname location
throw new Error "Location does not exist" unless fs.existsSync(location)
throw new Error "Location does not exist" unless fs.existsSync location

File.open path, 'w', (file) ->
return false if Digest.MD5.hexdigest(file.read()) is data.hash()
Expand Down
12 changes: 6 additions & 6 deletions examples/code.coffee
Expand Up @@ -13,7 +13,7 @@ run_loop = ->
wait()

# Objects:
dense_object_literal = {one: 1, two: 2, three: 3}
dense_object_literal = one: 1, two: 2, three: 3

spaced_out_multiline_object =
pi: 3.14159
Expand Down Expand Up @@ -56,15 +56,15 @@ race = ->
run()
walk()
crawl()
if tired then return sleep()
return sleep() if tired
race()

# Conditional assignment:
good or= evil
wine and= cheese

# 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

Expand All @@ -79,7 +79,7 @@ try
dogs_and_cats_living_together()
throw "up"
catch error
print(error)
print error
finally
clean_up()

Expand Down Expand Up @@ -130,8 +130,8 @@ wednesday = -> eat_breakfast(); go_to_work(); eat_dinner()

# Multiline strings with inner quotes.
story = "Lorem ipsum dolor \"sit\" amet, consectetuer adipiscing elit,
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna
aliquam erat volutpat. Ut wisi enim ad."
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna
aliquam erat volutpat. Ut wisi enim ad."

# Inheritance and calling super.
class Animal
Expand Down
8 changes: 4 additions & 4 deletions examples/computer_science/binary_search.coffee
Expand Up @@ -19,7 +19,7 @@ binary_search = (items, value) ->


# Test the function.
console.log 2 is binary_search [10, 20, 30, 40, 50], 30
console.log 4 is binary_search [-97, 35, 67, 88, 1200], 1200
console.log 0 is binary_search [0, 45, 70], 0
console.log(-1 is binary_search [0, 45, 70], 10)
console.log 2 is binary_search [10, 20, 30, 40, 50], 30
console.log 4 is binary_search [-97, 35, 67, 88, 1200], 1200
console.log 0 is binary_search [0, 45, 70], 0
console.log -1 is binary_search [0, 45, 70], 10
4 changes: 2 additions & 2 deletions examples/computer_science/bubble_sort.coffee
@@ -1,8 +1,8 @@
# A bubble sort implementation, sorting the given array in-place.
bubble_sort = (list) ->
for i in [0...list.length]
for j in [0...list.length - i]
[list[j], list[j+1]] = [list[j+1], list[j]] if list[j] > list[j+1]
for j in [0...list.length - i] when list[j] > list[j + 1]
[list[j], list[j+1]] = [list[j + 1], list[j]]
list


Expand Down
26 changes: 13 additions & 13 deletions examples/computer_science/linked_list.coffee
@@ -1,8 +1,8 @@
# "Classic" linked list implementation that doesn't keep track of its size.
class LinkedList

->
this._head = null # Pointer to the first item in the list.
constructor: ->
@_head = null # Pointer to the first item in the list.


# Appends some data to the end of the list. This method traverses the existing
Expand All @@ -12,10 +12,10 @@ class LinkedList
# Create a new node object to wrap the data.
node = data: data, next: null

current = this._head or= node
current = @_head or= node

if this._head isnt node
(current = current.next) while current.next
if @_head isnt node
current = current.next while current.next
current.next = node

this
Expand All @@ -27,11 +27,11 @@ class LinkedList
# Check for out-of-bounds values.
return null if index < 0

current = this._head or null
current = @_head or null
i = -1

# Advance through the list.
(current = current.next) while current and index > (i += 1)
current = current.next while current and index > ++i

# Return null if we've reached the end.
current and current.data
Expand All @@ -43,16 +43,16 @@ class LinkedList
# Check for out-of-bounds values.
return null if index < 0

current = this._head or null
current = @_head or null
i = -1

# Special case: removing the first item.
if index is 0
this._head = current.next
@_head = current.next
else

# Find the right location.
([previous, current] = [current, current.next]) while index > (i += 1)
[previous, current] = [current, current.next] while index > ++i

# Skip over the item to remove.
previous.next = current.next
Expand All @@ -63,7 +63,7 @@ class LinkedList

# Calculate the number of items in the list.
size: ->
current = this._head
current = @_head
count = 0

while current
Expand All @@ -76,7 +76,7 @@ class LinkedList
# Convert the list into an array.
toArray: ->
result = []
current = this._head
current = @_head

while current
result.push current.data
Expand All @@ -86,7 +86,7 @@ class LinkedList


# The string representation of the linked list.
toString: -> this.toArray().toString()
toString: -> @toArray().toString()


# Tests.
Expand Down
6 changes: 3 additions & 3 deletions examples/computer_science/luhn_algorithm.coffee
Expand Up @@ -7,13 +7,13 @@ is_valid_identifier = (identifier) ->
sum = 0
alt = false

for i in [identifier.length - 1..0] by -1
for c in identifier by -1

# Get the next digit.
num = parseInt identifier.charAt(i), 10
num = parseInt c, 10

# If it's not a valid number, abort.
return false if isNaN(num)
return false if isNaN num

# If it's an alternate number...
if alt
Expand Down
5 changes: 2 additions & 3 deletions examples/computer_science/merge_sort.coffee
Expand Up @@ -3,13 +3,12 @@ merge_sort = (list) ->

return list if list.length is 1

result = []
pivot = Math.floor list.length / 2
left = merge_sort list.slice 0, pivot
right = merge_sort list.slice pivot

while left.length and right.length
result.push(if left[0] < right[0] then left.shift() else right.shift())
result = while left.length and right.length
if left[0] < right[0] then left.shift() else right.shift()

result.concat(left).concat(right)

Expand Down
56 changes: 28 additions & 28 deletions examples/poignant.coffee
@@ -1,8 +1,11 @@
# Examples from the Poignant Guide.
# These are examples of syntax differences between CoffeeScript and Ruby,
# they won't run.

# ['toast', 'cheese', 'wine'].each { |food| print food.capitalize }

['toast', 'wine', 'cheese'].each (food) -> print food.capitalize()
print food.capitalize() for food in ['toast', 'wine', 'cheese']




Expand All @@ -14,10 +17,10 @@
# end

LotteryTicket =
get_picks: -> @picks
set_picks: (@picks) ->
get_purchased: -> @purchase
set_purchased: (@purchased) ->
get_picks: -> @picks
set_picks: (@picks) ->
get_purchased: -> @purchase
set_purchased: (@purchased) ->



Expand All @@ -42,13 +45,10 @@ LotteryDraw =
play: ->
result = LotteryTicket.new_random()
winners = {}
this.tickets.each (buyer, ticket_list) ->
ticket_list.each (ticket) ->
score = ticket.score result
return if score is 0
winners[buyer] or= []
winners[buyer].push [ticket, score]
this.tickets = {}
for buyer, ticketList of @tickets
for ticket in ticketList when (score = ticket.score result) isnt 0
(winners[buyer] or= []).push [ticket, score]
@tickets = {}
winners


Expand All @@ -64,7 +64,7 @@ LotteryDraw =

WishScanner =
scan_for_a_wish: ->
wish = this.read().detect (thought) -> thought.index('wish: ') is 0
wish = @read().detect (thought) -> thought.indexOf('wish: ') is 0
wish.replace 'wish: ', ''


Expand Down Expand Up @@ -109,28 +109,28 @@ Creature =

# This method applies a hit taken during a fight.
hit: (damage) ->
p_up = Math.rand this.charisma
p_up = Math.rand @charisma
if p_up % 9 is 7
this.life += p_up / 4
console.log "[" + this.name + " magick powers up " + p_up + "!]"
this.life -= damage
if this.life <= 0 then console.log "[" + this.name + " has died.]"
@life += p_up / 4
console.log "[#{@name} magick powers up #{p_up}!]"
@life -= damage
if @life <= 0 then console.log "[#{@name} has died.]"

# This method takes one turn in a fight.
fight: (enemy, weapon) ->
if this.life <= 0 then return console.log "[" + this.name + "is too dead to fight!]"
return console.log "[#{@name} is too dead to fight!]" if @life <= 0

# Attack the opponent.
your_hit = Math.rand this.strength + weapon
console.log "[You hit with " + your_hit + "points of damage!]"
your_hit = Math.rand @strength + weapon
console.log "[You hit with #{your_hit}points of damage!]"
enemy.hit your_hit

# Retaliation.
console.log enemy
if enemy.life > 0
enemy_hit = Math.rand enemy.strength + enemy.weapon
console.log "[Your enemy hit with " + enemy_hit + "points of damage!]"
this.hit enemy_hit
console.log "[Your enemy hit with #{enemy_hit}points of damage!]"
@hit enemy_hit



Expand All @@ -156,7 +156,7 @@ code_words.each (real, code) -> idea.replace(real, code)
# Save the jibberish to a new file
print "File encoded. Please enter a name for this idea: "
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



Expand All @@ -174,8 +174,8 @@ File.open "idea-" + idea_name + '.txt', 'w', (file) -> file.write idea

wipe_mutterings_from = (sentence) ->
throw new Error "cannot wipe mutterings" unless sentence.indexOf
while sentence.indexOf('(') >= 0
open = sentence.indexOf('(') - 1
close = sentence.indexOf(')') + 1
sentence = sentence.slice(0, open) + sentence.slice(close, sentence.length)
while '(' in sentence
open = sentence.indexOf('(')
close = sentence.indexOf(')')
sentence = "#{sentence[0...open]}#{sentence[close + 1..]}"
sentence
8 changes: 4 additions & 4 deletions examples/potion.coffee
Expand Up @@ -45,7 +45,7 @@ foods[2]
# (key, ' is a ', val) join print.

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.
Expand All @@ -54,7 +54,7 @@ for key, val of {dog: 'canine', cat: 'feline', fox: 'vulpine'}

class Person
print: ->
print 'My name is ' + @name + '.'
print "My name is #{@name}."


# p = Person ()
Expand All @@ -74,7 +74,7 @@ class Policeman extends Person
(@rank) ->

print: ->
print 'My name is ' + @name + " and I'm a " + @rank + '.'
print "My name is #{@name} and I'm a #{@rank}."

print new Policeman 'Constable'

Expand Down Expand Up @@ -180,7 +180,7 @@ if 3.gender?
# session = url query ? at ('session').

HomePage::get = (url) ->
session = url.query.session if url.query?
session = url.query?.session


# BTree = class: /left, /right.
Expand Down
4 changes: 2 additions & 2 deletions examples/web_server.coffee
Expand Up @@ -7,6 +7,6 @@ server = http.createServer (req, res) ->
res.write 'Hello, World!'
res.end()

server.listen 3000
server.listen PORT = 3000

console.log "Server running at http://localhost:3000/"
console.log "Server running at http://localhost:#{PORT}/"

0 comments on commit b859d92

Please sign in to comment.