forked from kbroman/ProgrammingNotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoffeescript.txt
More file actions
96 lines (72 loc) · 1.84 KB
/
coffeescript.txt
File metadata and controls
96 lines (72 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
Coffeescript notes
Installation:
brew update
brew install node
Within .bashrc:
export NODE_PATH=/usr/local/lib/node
npm install -g coffee-script
Check that it worked:
node -v
npm -v
coffee -v
======================================================================
Things I don't fully understand
apply and call
run = (f, args...) -> f(args...)
run2 = (f, args...) -> f.apply this, args
run3 = (f, args...) -> f.call this, args...
add = (a, b) -> a+b
console.log run add, -1, 3
console.log run2 add, -1, 3
console.log run3 add, -1, 3
splice
clearArray = (arr) ->
arr.splice 0, arr.length
return
x = [5, 3, 2]
console.log x
clearArray x
console.log x
-----
# copying arrays
a = [1,2,3]
b = a
c = a.slice(0)
a is b
not (a is c)
# sort strings as numbers
a = ['1', '12', '21', '3', '4']
a.sort((a,b) -> a-b)
# reduce, for summing an array
a = ['1', '12', '21', '3', '4']
a.reduce (t,s) -> Number(t) + Number(s)
a.map((d) -> Number(d)).reduce((t,s) -> t+s)
# create regular expression from a variable
ext = 'txt'
re = new RegExp("\.#{ext}$")
"blah.txt".match(re)
# list comprehensions for object
x = {a:1, b:2}
"#{k}: #{v}" for k,v of x
k for k of x
v for k,v of x
# create from prototype
y = Object.create x
y.d = 3
x.c = 4
k for k of y
k for own k of y # note use of "own"
# Multi-line strings
# (in REPL, use ctrl-v to switch between multi-line entry and not)
x = """blah blah blah
this is a multiline string
blah blah"""
# becomes 'blah blah blah\nthis is a multiline string\nblah blah'
# (also need ctrl-v for general code, like loops, that will need multiple lines)
# Again: for continuation lines (multiline code in the REPL)
# type ctrl-v (and then again ctrl-v to exit)
# delete element from hash
x = {a:1, b:2, c:3}
delete(x.b)
# another list comprehension example
z = ({x:Math.random(), y:Math.random()} for i in [1..20])