JavaScript 28 · Make the game easy to save and test

JavaScript lesson 28 of 50 · Intermediate · About 35 minutes

Create a small storage adapter so the same save and load rules work with a test store or a web browser.

At the workshop, Pip reaches toward a glowing crystal battery beside a copper coil, a gear and a map of the floating islands.
Mission Save a snapshot, load it and recover from an empty storage space.

Get ready

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

Connect. Give the game a store with two familiar methods. → Save. Write JSON text under one consistent key. → Load. Validate saved text or start a new game.
Connect → Save → Load

Understand the JavaScript in this lesson

Language to look for Map storage, Method shorthand, Adapter, String conversion, Null check.

1. Build a storage adapter with two methods

An adapter gives one tool the same way of working as another. This adapter uses a Map to remember text while this script runs. Its returned object has two methods named setItem and getItem. The shorter method syntax defines functions inside an object. Both methods can still reach the values Map created by the outer function.

setItem(key, text) { values.set(key, String(text)); },

2. Connect the game to that interface

The save function receives a store rather than choosing one itself. It gives that store the same key each time and saves the text made by encode. The loader reads by the exact same key. A missing key gives null, so the ternary chooses a new game. Any other value is decoded and validated.

return text === null ? Game.makeState() : decode(text);

3. Choose where the text lives

Here you pass an in-memory store, so you can repeat a test without previous browser saves getting in the way. A normal web page may offer window.localStorage, which also has these two methods and can remember text across page reloads. A browser can restrict that storage, especially for local files or private modes. The game rules work the same whichever store is passed.

const store = makeMemoryStorage();
Follow what happens step by step
  1. Load with an empty Map
    Pip starts at Hub.Why getItem returns null, so load makes a new state.
  2. Save Pip’s Workshop progress
    The Map receives encoded JSON text.Why save calls the store method with a consistent key.
  3. Read the same key
    Workshop and coil are restored.Why The loader sends the text to the validator.

Predict before you run Will a new call to makeMemoryStorage remember the earlier save?

Reveal the answer

It will create a fresh Map with no entries. Keep using the same store to retrieve its test saves.

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 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);
}
const store = makeMemoryStorage();
console.log("Empty store starts at:", load(store).room);
const workshop = Game.collect(Game.move(Game.makeState(), "Workshop"));
save(store, workshop);
const restored = load(store);
console.log("Restored:", restored.room, restored.energy, restored.bag[0]);

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–34
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 encode(state) {
Define encode. The body runs when the function is called, with inputs named state.
Line 31 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 34 function decode(text) {
Define decode. The body runs when the function is called, with inputs named text.
Lines 35–66
Line 35 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 36 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.
Line 37 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 39 const state = record.state;
Set up state. Keep this name attached to the same value.
Lines 40–49 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 50 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 52–53 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 54 throw new Error("Invalid rescue");
Stop this part of the program and report the problem to the caller or a matching catch block.
Lines 56–59 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 61 function makeMemoryStorage() {
Define makeMemoryStorage. The body runs when the function is called.
Line 62 const values = new Map();
Set up values. Keep this name attached to the same value. Use new to create a fresh Map object.
Lines 63–66 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.
Lines 69–82
Line 69 function save(store, state) {
Define save. The body runs when the function is called, with inputs named store, state.
Line 70 store.setItem("sky-island-v1", encode(state));
Call store.setItem with the values inside the parentheses.
Line 73 function load(store) {
Define load. The body runs when the function is called, with inputs named store.
Line 74 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 75 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 77 const store = makeMemoryStorage();
Set up store. Keep this name attached to the same value. Call makeMemoryStorage with the values inside the parentheses.
Line 78 console.log("Empty store starts at:", load(store).room);
Show a message or value in the output. Use it to watch the game work.
Line 79 const workshop = Game.collect(Game.move(Game.makeState(), "Workshop"));
Set up workshop. Keep this name attached to the same value. Call Game.collect with the values inside the parentheses.
Line 80 save(store, workshop);
Call save with the values inside the parentheses.
Line 81 const restored = load(store);
Set up restored. Keep this name attached to the same value. Call load with the values inside the parentheses.
Line 82 console.log("Restored:", restored.room, restored.energy, restored.bag[0]);
Show a message or value in the output. Use it to watch the game work.

Mission challenge

Make a second empty store and prove that saving to the first one does not affect the second one.

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