-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerators_for_efficient_iteration.js
75 lines (60 loc) · 1.5 KB
/
generators_for_efficient_iteration.js
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
"use strict";
function annotate(msg, fn) {
console.log("# BEGIN " + msg + " output\n")
fn()
console.log("\n# END\n")
}
// Like the old Python range vs xrange
// Generators can improve memory efficiency
function range(n, m) {
let ret = []
for (let i=n; i < m; i++) {
ret.push(i)
}
return ret
}
function* xrange(n, m) {
for (let i=n; i < m; i++) {
yield i;
}
}
annotate("range", function () {
for (let i of range(10, 20)) {
console.log(i)
}
})
annotate("xrange", function () {
for (let i of xrange(20, 30)) {
console.log(i)
}
})
annotate("custom iterator", function() {
// Aside on how Symbols work
console.log("Aside: Symbols are unique for each call")
let compareSymbols = 'Symbol("north") === Symbol("north")'
console.log(compareSymbols, "is", eval(compareSymbols), "\n")
// Let's say we have objects that have cardinal direction properties
// And we want to go through them one by one
const NW = Symbol("north west")
const N = Symbol("north")
const NE = Symbol("north east")
const E = Symbol("east")
const SE = Symbol("south east")
const S = Symbol("south")
const SW = Symbol("south west")
const W = Symbol("west")
let obj = {}
obj[Symbol.iterator] = function* () {
yield NW
yield N
yield NE
yield E
yield SE
yield S
yield SW
yield W
}
for (let i of obj) {
console.log("Direction:", i)
}
})