-
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathtest_array_of_objects.ts
More file actions
90 lines (77 loc) · 2.47 KB
/
test_array_of_objects.ts
File metadata and controls
90 lines (77 loc) · 2.47 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
// Test arrays containing class instances and typed objects
// Critical for static typing migration: array elements must preserve their class type
class Item {
name: string;
value: number;
constructor(name: string, value: number) {
this.name = name;
this.value = value;
}
display(): string {
return this.name + "=" + this.value;
}
}
// === Array of class instances ===
const items: Item[] = [
new Item("alpha", 1),
new Item("beta", 2),
new Item("gamma", 3),
];
console.log(items.length); // 3
console.log(items[0].name); // alpha
console.log(items[1].value); // 2
console.log(items[2].display()); // gamma=3
// === Push and access ===
items.push(new Item("delta", 4));
console.log(items.length); // 4
console.log(items[3].display()); // delta=4
// === Iterate with for loop ===
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].value;
}
console.log(total); // 10
// === Map over array of objects ===
const names = items.map((item: Item): string => item.name);
console.log(names.join(", ")); // alpha, beta, gamma, delta
// === Filter array of objects ===
const big = items.filter((item: Item): boolean => item.value > 2);
console.log(big.length); // 2
console.log(big[0].name); // gamma
// === Find in array of objects ===
const found = items.find((item: Item): boolean => item.name === "beta");
if (found) {
console.log(found.display()); // beta=2
}
// === Mutate objects through array reference ===
items[0].value = 100;
console.log(items[0].display()); // alpha=100
// === Array of objects passed to function ===
function sumValues(arr: Item[]): number {
let s = 0;
for (let i = 0; i < arr.length; i++) {
s += arr[i].value;
}
return s;
}
console.log(sumValues(items)); // 109 (100+2+3+4)
// === Nested class instances ===
class Container {
items: Item[];
constructor() { this.items = []; }
add(item: Item): void { this.items.push(item); }
count(): number { return this.items.length; }
getItem(index: number): Item { return this.items[index]; }
}
const box = new Container();
box.add(new Item("x", 10));
box.add(new Item("y", 20));
console.log(box.count()); // 2
console.log(box.getItem(0).display()); // x=10
console.log(box.getItem(1).display()); // y=20
// === Sort array of objects (by value) ===
const sorted = [new Item("c", 30), new Item("a", 10), new Item("b", 20)];
sorted.sort((a: Item, b: Item): number => a.value - b.value);
console.log(sorted[0].name); // a
console.log(sorted[1].name); // b
console.log(sorted[2].name); // c