-
Notifications
You must be signed in to change notification settings - Fork 34
/
js.Rmd
301 lines (200 loc) · 6.19 KB
/
js.Rmd
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# Just Enough JS <i class="fab fa-js-square"></i>
<script src="https://d3js.org/d3.v7.js"></script>
Basics: *IDVW*, pp. 36-52
Before JavaScript ES6, the 'var' keyword was used to declare a variable. Variables declared using the 'var' keyword are either globally or functionally scoped, they do not support block-level scope. Therefore, in JavaScript ES6, the 'let' keyword and 'const' keyword were introduced.
The 'let' keyword deals with a block scope. It can be reassigned but cannot be redeclared.
The 'const' keyword is also blocked scoped. It cannot be reassigned and cannot be redeclared.
As a general rule, you should always declare variables with 'const', if you realize that the value of the variable needs to change, go back and change it to 'let'.
For more detailed information regaring 'var', 'let' and 'const', please see [Difference between var, let, and const keyword in JavaScript](https://www.educative.io/answers/difference-between-var-let-and-const-keyword-in-javascript)
objects, arrays, arrays of objects, functions (and other things)
## Arrays of arrays
> <i class="fa fa-hand-o-right"></i> *Open the JavaScript Console* <i class="fa fa-terminal"></i>
``` js
// try me in the Console
const array_dataset = [[100, 75, 30], [200, 125, 20]];
d3.select("svg#arrays")
.selectAll("circle")
.data(array_dataset)
.enter()
.append("circle")
.attr("cx", d => d[0])
.attr("cy", d => d[1])
.attr("r", d => d[2])
.attr("fill", "red");
```
```{r, echo=FALSE, results='asis'}
makesvg("arrays")
```
## Arrays of objects
``` js
// Try me in the Console
const object_dataset = [
{cx: 100, cy: 150, fill: `red`},
{cx: 200, cy: 100, fill: `blue`}
];
d3.select("svg#objects")
.selectAll("circle")
.data(object_dataset)
.enter()
.append("circle")
.attr("cx", d => d.cx)
.attr("cy", d => d.cy)
.attr("r", "30")
.attr("fill", d => d.fill);
```
```{r, results='asis', echo=FALSE}
makesvg("objects")
```
See also: [JavaScript Array of Objects Tutorial](https://www.freecodecamp.org/news/javascript-array-of-objects-tutorial-how-to-create-update-and-loop-through-objects-using-js-array-methods/)
## `.map()`
What's the issue?
In R many operations are [vectorized](https://bookdown.org/rdpeng/rprogdatascience/vectorized-operations.html){target="_blank"}:
```{r}
sqrt(3)
x <- c(3, 5, 7)
sqrt(x)
```
Not so in JavaScript:
``` js
Math.sqrt(3); // Try me in the Console
```
``` js
const x = [3, 5, 7]; // Try me in the Console
Math.sqrt(x); // Doesn't work...
```
### Simple arrays
Use `.map()` to operate on each array element separately. The concept is similar to `lapply()` or `purrr::map()`, but unlike in R, it's needed for simple arrays.
**R**
```{r}
x <- c(3, 5, 7)
sqrt(x)
```
**JavaScript**
Do something to every element of a simple array:
``` js
// take the square root of each element
const x = [3, 5, 7]; // try me
x.map(Math.sqrt);
```
``` js
// multiply each element by 3
[4, 10, 12].map(d => d*3); // try me
```
``` js
// multiply each element by 3
[4, 10, 12].map(function(d) {return d*3;}); // try me
```
``` js
// multiply each element by its index
[10, 20, 30, 40].map((d, i) => d*i); // try me
```
**R: Sum two arrays**
```{r}
# sum two arrays
x <- 1:3
y <- 4:6
x + y
```
**JavaScript: Sum two arrays**
``` js
// sum two arrays
const x = [1, 2, 3];
const y = [4, 5, 6];
x + y // try me... what went wrong?
```
``` js
// sum two arrays
const x = [1, 2, 3];
const y = [4, 5, 6];
x.map((d, i) => d + y[i]); // try me
```
### Arrays of arrays
Do something to the first item of every element of a nested array:
``` js
[[1, 2], [3, 4]].map(d => Math.sqrt(d[0])) // try me
```
Sum up all items in each element of the array:
``` js
[[1, 2, 3], [4, 5, 6]].map(d => d[0] + d[1] + d[2]); // try me
```
Created a nested array out of a simple array:
``` js
[10, 20, 30].map(d => [d, Math.pow(d, 2)]);
```
### Create arrays of objects
Create an array of objects out of a simple array (note the parentheses around the object):
``` js
[10, 20, 30].map(d => ({n: d, nsq: Math.pow(d, 2)})); // try me
```
``` js
[10, 20, 30].map((d, i) => ({index: i, value: d})); // try me
```
## D3 sorting
Use `d3.sort()` rather than plain JavaScript options.
``` js
const y = [3, 1, 5, 12, 7]; // try me
d3.sort(y);
```
## D3 statistics
[link to API](https://github.com/d3/d3-array/blob/v1.2.4/README.md#statistics){target="_blank"}
D3 brings us back to familiar ground with functions that take an *array* and return a single value. Here are D3 functions with the same names and behavior as their R equivalents:
|R|D3|
|:-|:-|
|`min(x)`|`d3.min(x)`|
|`max(x)`|`d3.max(x)`|
|`sum(x)`|`d3.sum(x)`|
|`mean(x)`|`d3.mean(x)`|
|`median(x)`|`d3.median(x)`|
<br>
A few with different names:
|R|D3|
|:-|:-|
|`range(x)`|`d3.extent(x)`|
|`var(x)`|`d3.variance(x)`|
|`sd(x)`|`d3.deviation(x)`|
<br>
`d3.quantile()` takes a single value for `p`, not an array as in R. (In earlier versions of D3 it was necessary to [sort the array](just-enough-js.html#sorting) before finding quantiles, but this is no longer the case.)
|R|D3|
|:-|:-|
|`quantile(x)`|`d3.quantile(x, p)`|
Thus for a single quantile we have:
``` js
const x = [12, 34, 1, 43, 90, 72]; // try me
d3.quantile(x, .25);
```
https://github.com/d3/d3/blob/main/API.md#statistics
## D3 + `.map()`
D3 statistics functions combined with `.map()` can be helpful in a variety of situations.
Vectorizing a parameter, for example to mimic `quantile(x)` in R:
**R**
```{r}
x <- c(1, 12, 34, 43, 72, 90);
quantile(x)
```
**JavaScript**
``` js
const x = [1, 12, 34, 43, 72, 90]; // try me
[0, .25, .5, .75, 1].map(p => d3.quantile(x, p));
```
Sum up the first item of all elements in an array of arrays:
**R**
```{r}
l <- list(c(100, 200, 40), c(300, 150, 20))
sum(purrr::map_dbl(l, ~.x[1]))
```
**JavaScript**
``` js
const dataset = [[100, 200, 40], [300, 150, 20]]; // try me
d3.sum(dataset.map(d => d[0]));
```
Sum up all items in each array to create a simple array:
**R**
```{r}
l <- list(c(100, 200, 40), c(300, 150, 20))
purrr::map_dbl(l, ~sum(.x))
```
**JavaScript**
``` js
const dataset = [[100, 200, 40], [300, 150, 20]]; // try me
dataset.map(d => d3.sum(d));
```