Iterables and Generators
Spread and Destructuring
Spread and destructuring can pull values out of iterable data.
iterable spread
The spread operator `...` copies values from an iterable into a new array or argument list.
Spread and Destructuring
spread.ts
Replay: real traced execution (multi-file project)
const extraValue: number = 4;
const source: number[] = [1, 2, extraValue];
const copy: number[] = [...source];
const [first, second, third] = copy;
const total: number = first + second + third;
console.log(`copy=${copy.join(",")}`);
console.log(`total=${total}`);
const extraValue: number = 3;
const source: number[] = [1, 2, extraValue];
const copy: number[] = [...source];
const [first, second, third] = copy;
const total: number = first + second + third;
console.log(`copy=${copy.join(",")}`);
console.log(`total=${total}`);
const extraValue: number = 5;
const source: number[] = [1, 2, extraValue];
const copy: number[] = [...source];
const [first, second, third] = copy;
const total: number = first + second + third;
console.log(`copy=${copy.join(",")}`);
console.log(`total=${total}`);
extraValue ← 4, source ← 1,2,4, copy ← 1,2,4, first ← 1, second ← 2
1const extraValue→ 4: number = 4; //@extraValue=3, 52const source→ 1,2,4: number[] = [1, 2, extraValue4];3const copy→ 1,2,4: number[] = [...source1,2,4];4const [first→ 1, second→ 2, third→ 4] = copy→ 1,2,4;5const total→ 7: number = first→ 1 + second→ 2 + third4;67console.log(`copy=${copy1,2,4.join(",")}`);8console.log(`total=${total7}`);outputcopy=1,2,4 total=7
extraValue ← 3, source ← 1,2,3, copy ← 1,2,3, first ← 1, second ← 2
1const extraValue→ 3: number = 3;2const source→ 1,2,3: number[] = [1, 2, extraValue3];3const copy→ 1,2,3: number[] = [...source1,2,3];4const [first→ 1, second→ 2, third→ 3] = copy→ 1,2,3;5const total→ 6: number = first→ 1 + second→ 2 + third3;67console.log(`copy=${copy1,2,3.join(",")}`);8console.log(`total=${total6}`);outputcopy=1,2,3 total=6
extraValue ← 5, source ← 1,2,5, copy ← 1,2,5, first ← 1, second ← 2
1const extraValue→ 5: number = 5;2const source→ 1,2,5: number[] = [1, 2, extraValue5];3const copy→ 1,2,5: number[] = [...source1,2,5];4const [first→ 1, second→ 2, third→ 5] = copy→ 1,2,5;5const total→ 8: number = first→ 1 + second→ 2 + third5;67console.log(`copy=${copy1,2,5.join(",")}`);8console.log(`total=${total8}`);outputcopy=1,2,5 total=8