Correcting Results With with() and toSpliced()

The week 9 table is ranked, and the captains are messaging. United’s captain says Dynamo 3-1 United finished 3-2, and the committee may void Athletic 2-2 Wanderers. The results, a tuple in Python and a frozen array in the port, must stay as reported, so the corrections have to go into copies.

Ask for a Changed Copy

Python rebuilds the tuple from slices with RESULTS[:2] + (("Dynamo", 3, "United", 2),) + RESULTS[3:] and drops the draw with RESULTS[:1] + RESULTS[2:]. JavaScript has a copying method for each job, returning the changed copy in one call. In the port, each record is frozen too, as Python’s inner tuples are fixed:

Language: JavaScript
const RESULTS = Object.freeze([
  { home: "Rovers", homeGoals: 4, away: "Albion", awayGoals: 1 },
  { home: "Athletic", homeGoals: 2, away: "Wanderers", awayGoals: 2 },
  { home: "Dynamo", homeGoals: 3, away: "United", awayGoals: 1 },
]);
for (const match of RESULTS) {
  Object.freeze(match);
}

const ruling = Object.freeze({
  home: "Dynamo",
  homeGoals: 3,
  away: "United",
  awayGoals: 2,
});
const corrected = RESULTS.with(2, ruling);
const counted = RESULTS.toSpliced(1, 1);
console.log(corrected[2]);
console.log(counted);

Neither call throws, unlike POINTS.sort(), which throws a TypeError on a frozen array, because a copying method only reads its array. Both copies start from the three reported results, so corrected holds the 3-2 and counted keeps the 3-1:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.