JavaScript 30 · Prove the whole rescue works

JavaScript lesson 30 of 50 · Intermediate · About 45 minutes

Run a compact test suite that checks both successful rescues and mistakes players can make.

At the workshop, Pip reaches toward a glowing crystal battery beside a copper coil, a gear and a map of the floating islands.
Mission Test a blocked move, a saved game, a rejected save and a complete replay.

Get ready

Open Complete checkpoint below. Paste the JavaScript into a blank JavaScript editor and run it.

Assert a rule. Give every expected result an informative name. → Play the mission. Join the actions to check the complete game. → Round-trip the save. Compare the restored state with the expected finish.
Assert a rule → Play the mission → Round-trip the save

Understand the JavaScript in this lesson

Language to look for Assertions, Independent tests, Regression checks, Integration tests.

1. Write a test that tells you what failed

check takes a condition and a label. If the condition is false, it throws an Error whose message names the test that failed. If it is true, it prints a PASS line. A check turns the behaviour you expect into a repeatable question. Run the same tests after a change to catch a regression, which is a feature that used to work and has stopped working.

if (!condition) throw new Error("FAIL: " + label);

2. Start small with one rule at a time

The first check asks whether an illegal journey leaves the original state object in place. It compares object identity with ===, which is important because this rule deliberately returns the same object when blocked. Another check loads an empty store. Each test has a clear starting point, so it does not depend on a browser save left by another player.

check(Game.move(start, "Beacon") === start, "blocked route keeps state");

3. Connect the stages for a larger test

The last checks use a whole route and round-trip the final state through save and load. A round-trip sends values out through one format and reads them back. The tests compare room, bag length and rescue result. This integration test checks that several independent pieces still agree on how to exchange data.

check(restored.rescued && restored.bag.length === 2, "round-trip keeps the rescue");
Follow what happens step by step
  1. Run the small rule checks
    Blocked travel, empty storage and wrong versions pass.Why Each uses a known starting state and result.
  2. Replay the full flight
    The Beacon is repaired.Why Movement, collection and repair pass state between rules.
  3. Save and reload the finish
    The final rescue and two parts survive.Why The store, JSON and validator agree on the file shape.

Predict before you run If the flight no longer includes the final repair action, which check fails first?

Reveal the answer

The check labelled replay repairs the Beacon. Pip arrives at Beacon, but rescued is still false. The suite stops before the save round-trip.

Complete checkpoint

JavaScript · the instructions

const MAP = {
  Hub: ["Workshop", "Garden"],
  Workshop: ["Hub", "Garden"],
  Garden: ["Hub", "Workshop", "Beacon"],
  Beacon: ["Garden"]
};
const PARTS = { Workshop: "coil", Garden: "cell" };

function makeState() {
  return { room: "Hub", energy: 5, bag: [], rescued: false };
}
function move(state, destination) {
  const { room, energy } = state;
  if (!MAP[room].includes(destination) || energy < 1) {
    return state;
  }
  return { ...state, room: destination, energy: energy - 1 };
}
function collect(state) {
  const part = PARTS[state.room];
  if (!part || state.bag.includes(part)) return state;
  return { ...state, bag: [...state.bag, part] };
}
function repair(state) {
  if (state.room !== "Beacon") return state;
  if (!["coil", "cell"].every((part) => state.bag.includes(part))) return state;
  return { ...state, rescued: true };
}
const Game = Object.freeze({ makeState, move, collect, repair });
function apply(state, action) {
  switch (action.type) {
    case "move": return Game.move(state, action.destination);
    case "collect": return Game.collect(state);
    case "repair": return Game.repair(state);
    default: throw new Error("Unknown action: " + action.type);
  }
}
function encode(state) {
  return JSON.stringify({ version: 1, state });
}

function decode(text) {
  const record = JSON.parse(text);
  if (record === null || record.version !== 1) {
    throw new Error("Unsupported save version");
  }
  const state = record.state;
  if (
    !state ||
    !Object.hasOwn(MAP, state.room) ||
    !Number.isInteger(state.energy) ||
    state.energy < 0 || state.energy > 5 ||
    !Array.isArray(state.bag) ||
    !state.bag.every((part) => part === "coil" || part === "cell") ||
    new Set(state.bag).size !== state.bag.length ||
    typeof state.rescued !== "boolean"
  ) {
    throw new Error("Invalid game state");
  }
  if (state.rescued &&
      (state.room !== "Beacon" || state.bag.length !== 2)) {
    throw new Error("Invalid rescue");
  }
  return {
    room: state.room, energy: state.energy,
    bag: [...state.bag], rescued: state.rescued
  };
}
function makeMemoryStorage() {
  const values = new Map();
  return {
    setItem(key, text) { values.set(key, String(text)); },
    getItem(key) { return values.has(key) ? values.get(key) : null; }
  };
}

function save(store, state) {
  store.setItem("sky-island-v1", encode(state));
}

function load(store) {
  const text = store.getItem("sky-island-v1");
  return text === null ? Game.makeState() : decode(text);
}
function launch(seed) {
  if (!Number.isInteger(seed) || seed < 0 || seed > 99) {
    throw new Error("Choose a whole-number seed from 0 to 99");
  }
  const supplies = (seed * 17 + 11) % 3;
  return { ...Game.makeState(), energy: 3 + supplies };
}

function replay(seed, actions) {
  return actions.reduce((state, action) => apply(state, action), launch(seed));
}
const flight = [
  { type: "move", destination: "Workshop" },
  { type: "collect" },
  { type: "move", destination: "Garden" },
  { type: "collect" },
  { type: "move", destination: "Beacon" },
  { type: "repair" }
];
function check(condition, label) {
  if (!condition) throw new Error("FAIL: " + label);
  console.log("PASS:", label);
}

const start = launch(6);
check(Game.move(start, "Beacon") === start, "blocked route keeps state");
check(load(makeMemoryStorage()).room === "Hub", "empty store starts fresh");
let rejected = false;
try {
  decode('{"version":2}');
} catch (error) {
  rejected = error.message === "Unsupported save version";
}
check(rejected, "bad save version is rejected");

const finished = replay(6, flight);
check(finished.room === "Beacon" && finished.rescued, "replay repairs the Beacon");
const store = makeMemoryStorage();
save(store, finished);
const restored = load(store);
check(restored.rescued && restored.bag.length === 2, "round-trip keeps the rescue");
console.log("Five rescue checks passed.");

Read the JavaScript line by line

Open a small group of lines while you read the complete checkpoint. Blank lines separate ideas. Closing braces mark the end of a block. An ellipsis here means you can read the rest in the full program.

Lines 1–21
Lines 1–6 const MAP = { Hub: ["Workshop", "Garden"], Workshop: ["Hub", "Garden"], Garden: ["Hub", "Workshop", "Beacon"], Beacon: ["Garden"] };
Set up MAP. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
Line 7 const PARTS = { Workshop: "coil", Garden: "cell" };
Set up PARTS. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 9 function makeState() {
Define makeState. The body runs when the function is called.
Line 10 return { room: "Hub", energy: 5, bag: [], rescued: false };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
Line 12 function move(state, destination) {
Define move. The body runs when the function is called, with inputs named state, destination.
Line 13 const { room, energy } = state;
Set up { room, energy }. Keep this name attached to the same value.
Line 14 if (!MAP[room].includes(destination) || energy < 1) {
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation mark reverses a true-or-false test.
Line 15 return state;
Leave this function and send the value back to the caller.
Line 17 return { ...state, room: destination, energy: energy - 1 };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Three dots unpack the existing entries here.
Line 19 function collect(state) {
Define collect. The body runs when the function is called, with inputs named state.
Line 20 const part = PARTS[state.room];
Set up part. Keep this name attached to the same value. Work out what is inside the brackets first, then use it as the key or index.
Line 21 if (!part || state.bag.includes(part))
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation mark reverses a true-or-false test.
Lines 21–32
Line 21 return state;
Leave this function and send the value back to the caller.
Line 22 return { ...state, bag: [...state.bag, part] };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Three dots unpack the existing entries here.
Line 24 function repair(state) {
Define repair. The body runs when the function is called, with inputs named state.
Line 25 if (state.room !== "Beacon")
Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
Line 25 return state;
Leave this function and send the value back to the caller.
Line 26 if (!["coil", "cell"].every((part) => state.bag.includes(part)))
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test. Square brackets create an ordered array. Its first position is 0.
Line 26 return state;
Leave this function and send the value back to the caller.
Line 27 return { ...state, rescued: true };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Three dots unpack the existing entries here.
Line 29 const Game = Object.freeze({ makeState, move, collect, repair });
Set up Game. Keep this name attached to the same value. Prevent direct edits to the properties of this object.
Line 30 function apply(state, action) {
Define apply. The body runs when the function is called, with inputs named state, action.
Lines 31–32 switch (action.type) {
Compare one value with the case labels, then follow the matching branch.
Line 32 case "move":
Run this branch when its label matches.
Lines 32–44
Line 32 return Game.move(state, action.destination);
Leave this function and send the value back to the caller. Call Game.move with the values inside the parentheses.
Line 33 case "collect":
Run this branch when its label matches.
Line 33 return Game.collect(state);
Leave this function and send the value back to the caller. Call Game.collect with the values inside the parentheses.
Line 34 case "repair":
Run this branch when its label matches.
Line 34 return Game.repair(state);
Leave this function and send the value back to the caller. Call Game.repair with the values inside the parentheses.
Line 35 default:
Use this branch when no label matches.
Line 35 throw new Error("Unknown action: " + action.type);
Stop this part of the program and report the problem to the caller or a matching catch block.
Line 38 function encode(state) {
Define encode. The body runs when the function is called, with inputs named state.
Line 39 return JSON.stringify({ version: 1, state });
Leave this function and send the value back to the caller. Turn the JavaScript value into JSON text for a save or comparison.
Line 42 function decode(text) {
Define decode. The body runs when the function is called, with inputs named text.
Line 43 const record = JSON.parse(text);
Set up record. Keep this name attached to the same value. Turn JSON text into values. Invalid JSON throws an error.
Line 44 if (record === null || record.version !== 1) {
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The triple equals compares without converting the value’s type.
Lines 45–78
Line 45 throw new Error("Unsupported save version");
Stop this part of the program and report the problem to the caller or a matching catch block.
Line 47 const state = record.state;
Set up state. Keep this name attached to the same value.
Lines 48–57 if ( !state || !Object.hasOwn(MAP, state.room) || !Number.isInteger(state.energy) || state.energy < 0 || state.energy > 5 || …
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. Check whether the first value is greater than the second.
Line 58 throw new Error("Invalid game state");
Stop this part of the program and report the problem to the caller or a matching catch block.
Lines 60–61 if (state.rescued && (state.room !== "Beacon" || state.bag.length !== 2)) {
Run this part when the test is truthy. JavaScript evaluates the right side only when the left side is truthy. JavaScript tries the right side only when the left side is falsy.
Line 62 throw new Error("Invalid rescue");
Stop this part of the program and report the problem to the caller or a matching catch block.
Lines 64–67 return { room: state.room, energy: state.energy, bag: [...state.bag], rescued: state.rescued };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
Line 69 function makeMemoryStorage() {
Define makeMemoryStorage. The body runs when the function is called.
Line 70 const values = new Map();
Set up values. Keep this name attached to the same value. Use new to create a fresh Map object.
Lines 71–74 return { setItem(key, text) { values.set(key, String(text)); }, getItem(key) { return values.has(key) ? values.get(key) : null; } };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Create a function that this line can pass or save for later.
Line 77 function save(store, state) {
Define save. The body runs when the function is called, with inputs named store, state.
Line 78 store.setItem("sky-island-v1", encode(state));
Call store.setItem with the values inside the parentheses.
Lines 81–104
Line 81 function load(store) {
Define load. The body runs when the function is called, with inputs named store.
Line 82 const text = store.getItem("sky-island-v1");
Set up text. Keep this name attached to the same value. Call store.getItem with the values inside the parentheses.
Line 83 return text === null ? Game.makeState() : decode(text);
Leave this function and send the value back to the caller. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Line 85 function launch(seed) {
Define launch. The body runs when the function is called, with inputs named seed.
Line 86 if (!Number.isInteger(seed) || seed < 0 || seed > 99) {
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation mark reverses a true-or-false test.
Line 87 throw new Error("Choose a whole-number seed from 0 to 99");
Stop this part of the program and report the problem to the caller or a matching catch block.
Line 89 const supplies = (seed * 17 + 11) % 3;
Set up supplies. Keep this name attached to the same value. The percent sign gives the remainder after division. Plus adds numbers or joins text, depending on its values.
Line 90 return { ...Game.makeState(), energy: 3 + supplies };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Three dots unpack the existing entries here.
Line 93 function replay(seed, actions) {
Define replay. The body runs when the function is called, with inputs named seed, actions.
Line 94 return actions.reduce((state, action) => apply(state, action), launch(seed));
Leave this function and send the value back to the caller. Combine the entries into a single result, one entry at a time.
Lines 96–103 const flight = [ { type: "move", destination: "Workshop" }, { type: "collect" }, { type: "move", destination: "Garden" }, { type: "collect" }, …
Set up flight. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0. Braces create an object. Properties give names to the stored values.
Line 104 function check(condition, label) {
Define check. The body runs when the function is called, with inputs named condition, label.
Lines 105–118
Line 105 if (!condition)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 105 throw new Error("FAIL: " + label);
Stop this part of the program and report the problem to the caller or a matching catch block.
Line 106 console.log("PASS:", label);
Show a message or value in the output. Use it to watch the game work.
Line 109 const start = launch(6);
Set up start. Keep this name attached to the same value. Call launch with the values inside the parentheses.
Line 110 check(Game.move(start, "Beacon") === start, "blocked route keeps state");
Call check with the values inside the parentheses.
Line 111 check(load(makeMemoryStorage()).room === "Hub", "empty store starts fresh");
Call check with the values inside the parentheses.
Line 112 let rejected = false;
Set up rejected. Give this name a starting value that later code can change.
Line 113 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 114 decode('{"version":2}');
Call decode with the values inside the parentheses.
Line 115 catch (error) {
Run this block if the try block throws an error.
Line 116 rejected = error.message === "Unsupported save version";
The triple equals compares without converting the value’s type. Store the result in the name or property to the left.
Line 118 check(rejected, "bad save version is rejected");
Call check with the values inside the parentheses.
Lines 120–126
Line 120 const finished = replay(6, flight);
Set up finished. Keep this name attached to the same value. Call replay with the values inside the parentheses.
Line 121 check(finished.room === "Beacon" && finished.rescued, "replay repairs the Beacon");
Call check with the values inside the parentheses.
Line 122 const store = makeMemoryStorage();
Set up store. Keep this name attached to the same value. Call makeMemoryStorage with the values inside the parentheses.
Line 123 save(store, finished);
Call save with the values inside the parentheses.
Line 124 const restored = load(store);
Set up restored. Keep this name attached to the same value. Call load with the values inside the parentheses.
Line 125 check(restored.rescued && restored.bag.length === 2, "round-trip keeps the rescue");
Call check with the values inside the parentheses.
Line 126 console.log("Five rescue checks passed.");
Show a message or value in the output. Use it to watch the game work.

Mission challenge

Write a sixth test for a missing Cell. Give Pip only the coil at Beacon and confirm the repair is refused.

Change one piece at a time. Run the checkpoint again and compare what you expected with what actually happened.