Archive

Archive for the ‘coffeescript’ Category

Array min, max with Coffeescript

September 19, 2012 Leave a comment

Quite simple actually:


Array::max=->
  Math.max.apply(null, this)

Array::min=->
  Math.min.apply(null, this)

a=[6, 5, 17, -3, 4.5]
console.log a.max()
console.log a.min()

Outputs:
17
-3

Advertisements
Categories: coffeescript, Programming

Learning CoffeeScript

June 10, 2012 2 comments

Practice 1: Define a Student class, make some new instances and classify them into two arrays based on the student scores

class Student
    constructor:(@gender, @score)->

s1=new Student('M', 45)
s2=new Student('F', 78)
s3=new Student('F', 59)
s4=new Student('M', 99)

passed=[]
failed=[]
(if s.score>59 then passed else failed).push s for s in [s1, s2, s3, s4]
console.log passed
console.log failed

Practice 2: Array filtering

pr=(items, lbl)->
    console.log "==#{lbl}=="
    for item, i in items
        console.log "Item #{i}: #{item}"
    false

a=[1..9]

odd=(item for item in a when item%2)
even=(item for item in a when item%2==0)
double=(item*2 for item in a)

pr odd, "odd"
pr even, "even"
pr double, "double"

Practice 3: more about class

class Candidate
    constructor:(@approval_rate)->

class Election
    elect:(candidate)->
        candidate.approval_rate>0.5


e=new Election
console.log e.elect( new Candidate(0.34) )
console.log e.elect( new Candidate(0.59) )

Practice 4: serial_maker (based on
JavaScript: The Good Parts by Douglas Crockford
Chap 4.12)

class SerialMaker
    constructor:(@prefix='Q', @start=0)->
    gen_seq:()->
        @start+=1
        @prefix+@start

sm=new SerialMaker('SQ')
console.log sm.gen_seq()
console.log sm.gen_seq()
console.log sm.gen_seq()

Practice 5: (added 7/12/2012) Self-invoking constructor

class Person
    constructor:(name='no name')->
        return new Person(name) if !(@ instanceof Person)
        @name=name

    id:->
        return @name

    isrich:true


p1=Person('Freedom')
# or the above line can be written as 
# p1=new Person('Freedom')
# the result is exactly the same and the
# benefit is user doesn't need to worry about forgetting using the "new" keyword
console.log p1.id() + ','+ p1.isrich

Reference: http://arcturo.github.com/library/coffeescript/index.html

Categories: coffeescript, Programming