-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathjavascript.txt
More file actions
203 lines (160 loc) · 5.36 KB
/
javascript.txt
File metadata and controls
203 lines (160 loc) · 5.36 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// JavaScript ES6 notes
// Destructuring assignment
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
var a,b;
[a,b] = [1,2];
var chartOpts = {h:300, linecolor:"slateblue"};
var h, w, fill, linecolor;
({h=900, w=600, fill, linecolor} = chartOpts);
// h assigned chartOpts.h
// w assigned default value, 600
// linecolor assigned chartOpts.linecolor
// fill is undefined
// Template strings
var x = 30;
y = `x + 20 = ${x+20}`;
// need to use backticks and ${}
// loops
while(1) { }
for(let i=0; i<x.length; i++) {}
for(i in x) {} // loop over keys in object, or indices of array
for(xv of x) {} // loop over values of array
// break, continue
x = [1,3,9]
for(i of x) {}
for(xv in x) {}
y = {a:5, b:10, c:11}
for(key in y) {} // can't use for(key of y) {}
// .call, .apply
// .call
// call a function as if it were a method for the provided object
function greet() { return `Hello, my name is ${this.name}.`; }
greet.call({name: "Fisher"});
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
}
bruce = { name: "Bruce" }
update.call(bruce, 1969, "statistician");
// .apply is like .call, but taking extra args as an array
update.apply(bruce, [1972, "writer"]);
// you can use this to pass an array to Math.min or Math.max
x = [1, 23, -3, 4, 5]
Math.min.apply(null, x)
Math.max.apply(null, x)
// can also use ... (the "spread" operator)
Math.min(...x)
Math.max(...x)
// .bind permanently attaches an object (as "this") to a function
updateBruce = update.bind(bruce)
// .map, .filter with =>
x = [1,3,0,-2]
x.filter( d => d > 0 )
x.map( d => d**2 )
// template literals (expressions in strings)
// backticks and ${}
x = 5
y = `blah: ${x}`
//////////////////////////////////////////////////////////////////////
// working through Eloquent Javascript
// free online https://eloquentjavascript.net
// with code "playground" at https://eloquentjavascript.net/code
// backtick strings have variable insertion
let x = “blah”;
let y = `blah blah ${ x }`;
// use Number() to convert to number
let z = 5 ** 2 + “50”;
let w = 5 ** 2 + Number(“50”); // <- Number() turns a value into a number
// use || operator to allow defaults
w || “default”
let x = {a: “5”, b: 2};
x.c || “default”; // <- x.c is undefined
// check if not a number
Number.isNaN( x ) // <- test if x is a number
// copy properties from one object to another
x = {a: 1, b: 2}
Object.assign(x, {b: 3, c: 2})
// shortcut for defining an object
events = [“work”, “sleep”, “eat”]
tired = true
x = {events, tired}
// same as:
x = {events: [“work”, “sleep”, “eat”], tired: true}
// looping over arrays
for(let i=0; i<v.length; i++) { x = v[i]; }
for(let x of v) { }
for(let i in v) { x = v[i]; } // <- “in” to loop over the index
// array methods
x = [“work”, “sleep”, “eat”]
x.includes(“eat”)
// push and pop to add to end of array
x = [1, 2, 3]
x.push(5)
x.pop()
// unshift and shift to add to beginning of array
x.unshift(5)
x.shift()
// note that push and unshift return the new length of the array
// indexOf, lastIndexOf (also include optional 2nd arg indicating where to start search)
x = [“egg”, “waffle”, “pancake”, “egg”, “bagel”]
x.indexOf(“egg”)
x.lastIndexOf(“egg”)
x.indexOf(“egg”, 2)
// also findIndex which is like indexOf but takes a function
x.findIndex( v => v == “pancake” )
// slice
x = [“egg”, “waffle”, “pancake”, “egg”, “bagel”]
x.slice(2) // index 2 to end of array
x.slice(2,4) // includes first index not the last one
x.slice() // copies the array
x.slice(2,2) // empty array
“aardvark”.slice(4,7)
// concat
x.concat(5)
x.concat([5,7])
“a“.concat(“ardvark”)
// other string methods
“one two three”.indexof(“e”)
“one two three”.indexof(“ee”)
“one”.toUpperCase()
“50”.padStart(5, “0”)
“hello there dude”.split(“ “)
words.join(“ “)
“ ya ya “.trim()
“LA “.repeat(8)
// rest parameters
function max(...numbers) { }
// can also call function to spread out an array
Math.max(...[1, 5, 3, 7, -11])
// can use it to shove an array into another
x = [2,4,8]
y = [8, ...x, -3]
// can do sort of the reverse, array arg that names the values
function phi( [n11, n10, n01, n00] ) { }
// convert to and from json
x = JSON.stringify({events:[“work”, “eat”, “sleep”], tired:true})
y = JSON.parse(x)
// map, reduce, filter, some
[0,1,2,3].map(v => v+2)
[0,1,2,3].map(v => v+2).filter(v => v < 3)
[0,1,2,3].some(v => v < 1)
[0,1,2,3].map(v => v+1).some(v => v < 1)
[0,1,2,3].reduce((a,b) => a+b)
// these two things are the same
// (shortcut if you’re just looking at a particular part of an object)
x = [{name:”elf”}, {name:”deer”}, {name:”green bay”}, {name:”shelf”}]
x.filter( v => v.name==“deer” )
x.filter( ({name}) => name==“deer” ) // note need for () around the {name}
// debugging code
// ctrl-shift-j to open debugger tools
debugger // halt code at that point; can then step through while inspecting
// regular expressions
regex = new RegEx("^[01]+$");
regex2 = /\b[01]+\b/; // \b = word boundary
regex.test("0110001");
regex.match("0110001"); // vector
"0110001".match(regex);
result = "001x 001011 00201".match(regex2);
result.index;
result2 = regex2.exec("001x 001011 00201"); // equivalent
"Broman, Karl".replace(/(\w+), (\w+)/, "$2 $1")