Arrays and Tuples
Tuples
Tuples describe arrays with a fixed order and known element types.
tuple
A tuple such as `[string, number]` stores values in fixed positions with fixed types.
Tuples
tuple.ts
Replay: real traced execution (multi-file project)
const attempts: number = 2;
const result: [string, number] = ["login", attempts];
const action: string = result[0];
const count: number = result[1];
console.log(`${action}: ${count}`);
const attempts: number = 1;
const result: [string, number] = ["login", attempts];
const action: string = result[0];
const count: number = result[1];
console.log(`${action}: ${count}`);
const attempts: number = 4;
const result: [string, number] = ["login", attempts];
const action: string = result[0];
const count: number = result[1];
console.log(`${action}: ${count}`);
attempts ← 2, result ← login,2, action ← login, result[0] ← login
1const attempts→ 2: number = 2; //@attempts=1, 42const result→ login,2: [string, number] = ["login", attempts2];34const action→ login: string = result[0]→ login;5const count→ 2: number = result[1]→ 2;67console.log(`${actionlogin}: ${count2}`);outputlogin: 2
attempts ← 1, result ← login,1, action ← login, result[0] ← login
1const attempts→ 1: number = 1;2const result→ login,1: [string, number] = ["login", attempts1];34const action→ login: string = result[0]→ login;5const count→ 1: number = result[1]→ 1;67console.log(`${actionlogin}: ${count1}`);outputlogin: 1
attempts ← 4, result ← login,4, action ← login, result[0] ← login
1const attempts→ 4: number = 4;2const result→ login,4: [string, number] = ["login", attempts4];34const action→ login: string = result[0]→ login;5const count→ 4: number = result[1]→ 4;67console.log(`${actionlogin}: ${count4}`);outputlogin: 4
Follow the Tuple
attemptsstarts as2.resultstores two fixed positions:"login"first, thenattempts.actionreadsresult[0], so it becomeslogin.countreadsresult[1], so it becomes2.- The program prints
login: 2. | tuple position | value | local name | | --- | --- | --- | |result[0]| login |action| |result[1]| 2 |count|
Exercise: tuple.ts
Reproduce login: 2, then use the pinned attempts variants 1 and 4 to predict login: 1 and login: 4.