forked from mbebenita/LLJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstructs-members.ljs
74 lines (65 loc) · 1.86 KB
/
structs-members.ljs
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
let assert = require("assert");
extern describe, it, Math;
struct Point {
int x, y;
function Point (int x, int y) {
this->x = x;
this->y = y;
}
function toString() {
return "{x: " + this->x + ", y: " + this->y + "}";
}
function distanceTo(Point * other) {
let Line l (this->x, this->y, other->x, other->y);
return l.getLength();
}
}
struct Line {
Point a, b;
function Line (int x1, int y1, int x2, int y2) {
this->a.x = x1;
this->a.y = y1;
this->b.x = x2;
this->b.y = y2;
}
function float getLength() {
let float dx = this->a.x - this->b.x;
let float dy = this->a.y - this->b.y;
return float(Math.sqrt(dx * dx + dy * dy));
}
function toString() {
return "{" + this->a.toString() + " -> " + this->b.toString() + "}";
}
}
function floatIsEqual(a, b) {
let d = a - b;
if (d < 0) {
d *= -1;
}
return d < 0.001;
}
describe('Member Functions', function() {
it('allocates structs on the heap and call methods', function () {
let Point * p = new Point(1, 2);
assert (p->toString() === "{x: 1, y: 2}");
let Line * l = new Line(1, 2, 3, 4);
assert (l->toString() === "{{x: 1, y: 2} -> {x: 3, y: 4}}");
assert (floatIsEqual(l->getLength(), 2.8284271247461903));
});
it('allocates structs on the stack and call methods', function () {
let Line l1 (1, 2, 3, 4), l2 (2, 3, 4, 5), *l3;
assert (l1.toString() === "{{x: 1, y: 2} -> {x: 3, y: 4}}");
assert (l1.a.toString() === "{x: 1, y: 2}");
assert (l1.b.toString() === "{x: 3, y: 4}");
});
it('allocates structs on the stack and call methods', function () {
for (let int i = 0; i < 10; i++) {
let Point * k = new Point(1, 2);
assert (k->toString() === "{x: 1, y: 2}");
}
for (let int i = 0; i < 10; i++) {
let Point a (i, 1), b (i, 2);
assert (a.distanceTo(&b) === 1);
}
});
});